Spaces:
Sleeping

File size: 11,695 Bytes
da4b58e
 
 
 
 
 
 
 
 
449fffb
 
da4b58e
 
 
449fffb
da4b58e
201f02a
 
449fffb
da4b58e
201f02a
449fffb
 
 
da4b58e
449fffb
 
 
 
 
da4b58e
449fffb
da4b58e
 
449fffb
 
 
 
 
 
 
 
201f02a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
449fffb
da4b58e
449fffb
 
da4b58e
 
449fffb
 
da4b58e
 
 
449fffb
da4b58e
 
201f02a
673acc0
449fffb
da4b58e
 
 
 
201f02a
 
 
 
673acc0
 
 
 
201f02a
673acc0
449fffb
da4b58e
449fffb
 
da4b58e
 
 
 
449fffb
201f02a
 
 
 
 
 
449fffb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da4b58e
449fffb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
201f02a
449fffb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
201f02a
449fffb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da4b58e
449fffb
 
da4b58e
 
 
 
 
449fffb
 
 
 
 
 
 
 
 
201f02a
 
 
 
 
 
449fffb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da4b58e
449fffb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
201f02a
449fffb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
"""Google Drive helpers for transcript/source + state persistence.

Production mode (Hugging Face Spaces):
    - Uses a service account JSON provided via env var
        `GOOGLE_SERVICE_ACCOUNT_JSON` (stringified JSON).
    - Optional fallback: `GOOGLE_SERVICE_ACCOUNT_FILE` path to a JSON file.
    - Folder is configured via `GOOGLE_DRIVE_FOLDER_ID`.

No browser OAuth flow is required at runtime.
"""

from __future__ import annotations

import io
import json
import os
import sys
import traceback
from datetime import datetime
from pathlib import Path
from typing import Any, Optional

from google.oauth2.service_account import Credentials
from googleapiclient.discovery import build
from googleapiclient.http import MediaIoBaseDownload, MediaIoBaseUpload

# ─────────────────────────────────────────────────────────────────────────────
# Configuration
# ─────────────────────────────────────────────────────────────────────────────

SCOPES = ["https://www.googleapis.com/auth/drive"]

# Default fallback so local dev still works without env var.
_DEFAULT_FOLDER_ID = "1RkjxApl2WRAw2gRzuw8yESPNV9quGmQo"

# Local token cache (for user OAuth2 tokens)
TOKENS_CACHE_DIR = Path(__file__).parent / ".drive_tokens"
TOKENS_CACHE_DIR.mkdir(exist_ok=True)

SESSION_METADATA_FILE = TOKENS_CACHE_DIR / "session_metadata.json"


def format_drive_diagnostic(
    action: str,
    researcher_id: str = "",
    file_id: str = "",
    file_name: str = "",
    error: Exception | None = None,
    extra: dict[str, Any] | None = None,
) -> str:
    """Return a copyable plain-text block for troubleshooting Drive issues."""
    info = {
        "GOOGLE_SERVICE_ACCOUNT_JSON": "SET" if os.environ.get("GOOGLE_SERVICE_ACCOUNT_JSON", "").strip() else "MISSING",
        "GOOGLE_SERVICE_ACCOUNT_FILE": os.environ.get("GOOGLE_SERVICE_ACCOUNT_FILE", "").strip() or "MISSING",
        "GOOGLE_DRIVE_FOLDER_ID": os.environ.get("GOOGLE_DRIVE_FOLDER_ID", _DEFAULT_FOLDER_ID).strip() or "MISSING",
    }
    lines = [
        "=== DRIVE DEBUG START ===",
        f"action: {action}",
        f"researcher_id: {researcher_id or 'MISSING'}",
        f"file_id: {file_id or 'MISSING'}",
        f"file_name: {file_name or 'MISSING'}",
        f"service_account_json: {info['GOOGLE_SERVICE_ACCOUNT_JSON']}",
        f"service_account_file: {info['GOOGLE_SERVICE_ACCOUNT_FILE']}",
        f"drive_folder_id: {info['GOOGLE_DRIVE_FOLDER_ID']}",
    ]
    if extra:
        for key, value in extra.items():
            lines.append(f"{key}: {value}")
    if error is not None:
        lines.append(f"error_type: {type(error).__name__}")
        lines.append(f"error_message: {error}")
        lines.append("traceback:")
        lines.extend(traceback.format_exception(type(error), error, error.__traceback__))
    lines.append("=== DRIVE DEBUG END ===")
    return "\n".join(lines)


def _log_drive_diagnostic(*args, **kwargs) -> str:
    block = format_drive_diagnostic(*args, **kwargs)
    print(block, file=sys.stderr)
    return block


# ─────────────────────────────────────────────────────────────────────────────
# Credentials / service bootstrap
# ─────────────────────────────────────────────────────────────────────────────

def _folder_id() -> str:
    return os.environ.get("GOOGLE_DRIVE_FOLDER_ID", _DEFAULT_FOLDER_ID).strip()


def _service_account_info() -> Optional[dict]:
    raw = os.environ.get("GOOGLE_SERVICE_ACCOUNT_JSON", "").strip()
    if raw:
        try:
            return json.loads(raw)
        except json.JSONDecodeError as e:
            _log_drive_diagnostic("load_service_account_info", error=e)
            return None

    path = os.environ.get("GOOGLE_SERVICE_ACCOUNT_FILE", "").strip()
    if path:
        p = Path(path)
        if not p.exists():
            _log_drive_diagnostic(
                "load_service_account_file",
                extra={"path": path, "exists": False},
            )
            return None
        try:
            return json.loads(p.read_text(encoding="utf-8"))
        except json.JSONDecodeError as e:
            _log_drive_diagnostic("load_service_account_file", extra={"path": path, "exists": True}, error=e)
            return None

    return None


def get_drive_service(_: str = "") -> Optional[object]:
    """Return an authenticated Drive service (service-account), else None."""
    info = _service_account_info()
    if not info:
        return None
    try:
        creds = Credentials.from_service_account_info(info, scopes=SCOPES)
        return build("drive", "v3", credentials=creds)
    except Exception as e:
        _log_drive_diagnostic("build_drive_service", error=e)
        return None


# ─────────────────────────────────────────────────────────────────────────────
# File Operations
# ─────────────────────────────────────────────────────────────────────────────

def list_transcripts(service: object) -> list[dict]:
    """
    List all transcript files in the shared folder.
    Returns list of dicts: {"name": str, "id": str, "modified_time": str}
    """
    if not service:
        return []

    try:
        query = f"'{_folder_id()}' in parents and trashed=false"
        results = service.files().list(
            q=query,
            spaces='drive',
            fields='files(id, name, modifiedTime, mimeType)',
            pageSize=100,
        ).execute()
        
        files = results.get('files', [])
        
        # Filter for transcript files (txt, vtt, json)
        transcripts = [
            {
                "name": f["name"],
                "id": f["id"],
                "modified_time": f.get("modifiedTime", ""),
            }
            for f in files
            if f["name"].endswith(('.txt', '.vtt', '.json'))
        ]
        
        # Sort by modified time, newest first
        transcripts.sort(key=lambda x: x["modified_time"], reverse=True)
        return transcripts
    except Exception as e:
        _log_drive_diagnostic("list_transcripts", error=e)
        return []


def read_file_from_drive(service: object, file_id: str) -> str:
    """
    Read a file from Google Drive and return its contents as string.
    Streams the file to avoid loading entire file into memory.
    """
    if not service:
        raise RuntimeError("Not authenticated with Google Drive")

    try:
        request = service.files().get_media(fileId=file_id)
        file_obj = io.BytesIO()
        downloader = MediaIoBaseDownload(file_obj, request)
        
        done = False
        while not done:
            _, done = downloader.next_chunk()
        
        file_obj.seek(0)
        return file_obj.read().decode('utf-8')
    except Exception as e:
        _log_drive_diagnostic("read_file_from_drive", file_id=file_id, error=e)
        raise RuntimeError(f"Error reading file from Drive: {e}")


def write_session_to_drive(
    service: object,
    researcher_name: str,
    session_id: str,
    state_data: dict,
) -> str:
    """
    Write session state JSON to Google Drive (in the transcripts folder).
    Returns the file ID of the written file.
    Allows memory liberation β€” state is persisted, not cached in RAM.
    """
    if not service:
        raise RuntimeError("Not authenticated with Google Drive")

    filename = f"{researcher_name}_{session_id}_state.json"
    
    try:
        file_metadata = {
            "name": filename,
            "parents": [_folder_id()],
        }
        
        media = MediaIoBaseUpload(
            io.BytesIO(json.dumps(state_data, indent=2, ensure_ascii=False).encode("utf-8")),
            mimetype="application/json",
            resumable=False,
        )
        
        file = service.files().create(
            body=file_metadata,
            media_body=media,
            fields='id'
        ).execute()
        
        return file.get('id')
    except Exception as e:
        _log_drive_diagnostic(
            "write_session_to_drive",
            researcher_id=researcher_name,
            file_name=filename,
            error=e,
        )
        raise RuntimeError(f"Error writing session to Drive: {e}")


def load_session_from_drive(
    service: object,
    researcher_name: str,
) -> Optional[dict]:
    """
    Find and load the most recent session for a researcher.
    Returns session state dict, or None if not found.
    """
    if not service:
        return None

    try:
        # Search for files matching pattern: researcher_name_*_state.json
        query = (
            f"'{_folder_id()}' in parents and "
            f"name contains '{researcher_name}' and "
            f"name contains '_state.json' and "
            f"trashed=false"
        )
        
        results = service.files().list(
            q=query,
            spaces='drive',
            fields='files(id, name, modifiedTime)',
            pageSize=10,
            orderBy='modifiedTime desc',
        ).execute()
        
        files = results.get('files', [])
        if not files:
            return None
        
        # Load the most recent session file
        latest_file = files[0]
        request = service.files().get_media(fileId=latest_file['id'])
        file_obj = io.BytesIO()
        downloader = MediaIoBaseDownload(file_obj, request)
        
        done = False
        while not done:
            _, done = downloader.next_chunk()
        
        file_obj.seek(0)
        return json.loads(file_obj.read().decode('utf-8'))
    except Exception as e:
        _log_drive_diagnostic("load_session_from_drive", researcher_id=researcher_name, error=e)
        return None


# ─────────────────────────────────────────────────────────────────────────────
# Session Metadata
# ─────────────────────────────────────────────────────────────────────────────

def register_researcher(researcher_name: str) -> None:
    """Register a researcher in the local metadata (for quick lookup)."""
    metadata = {}
    if SESSION_METADATA_FILE.exists():
        metadata = json.loads(SESSION_METADATA_FILE.read_text())
    
    if researcher_name not in metadata:
        metadata[researcher_name] = {
            "created_at": datetime.now().isoformat(),
        }
        SESSION_METADATA_FILE.write_text(json.dumps(metadata, indent=2))


def list_researchers() -> list[str]:
    """Get list of all registered researchers."""
    if not SESSION_METADATA_FILE.exists():
        return []
    
    metadata = json.loads(SESSION_METADATA_FILE.read_text())
    return list(metadata.keys())