legacy-code-challenge-v2 / google_sheets_logger.py
refaelz's picture
Deploy updated challenge app to HF Space v2
5f3b513
Raw History Blame Contribute Delete
10.7 kB
"""
google_sheets_logger.py โ€” Optional Google Sheets integration for submission logging
This module provides automatic logging of student submissions to Google Sheets.
If not configured (no GOOGLE_SHEET_ID), it silently fails and the system continues normally.
"""
import os
import json
from datetime import datetime
from typing import Optional
from dotenv import load_dotenv
load_dotenv()
SUMMARY_HEADERS = [
"ืชืืจื™ืš ื•ืฉืขื”",
"ืฉื ืกื˜ื•ื“ื ื˜",
"ืืชื’ืจ",
"GitHub Repository",
"ืงื•ื‘ืฅ ื™ืขื“",
"ืฆื™ื•ืŸ",
"ื”ื™ื ื˜ื™ื",
"ื˜ืกื˜ื™ื ืฉืขื‘ืจื•",
"ื”ืฆืœื™ื—?",
"ืกื•ื’ ืชื•ืฆืื”",
"ื ื’ืขื” ื‘ืคื•ื ืงืฆื™ื™ืช ื‘ืื’?",
"ืชื™ืื•ืจ ื”ื‘ืื’",
"ื”ืชื›ืชื‘ื•ืช ืขื ื”ืฆ'ืื˜",
"Hugging Face username",
]
def _service_account_identity(service_account_json: str) -> str:
if not service_account_json:
return ""
try:
info = json.loads(service_account_json)
except Exception:
return ""
return info.get("client_email", "")
def _format_google_sheets_error(exc: Exception, sheet_id: str, service_account_json: str) -> str:
service_account_email = _service_account_identity(service_account_json)
spreadsheet_hint = (
f"Spreadsheet {sheet_id} was not found or is not shared with {service_account_email}."
if service_account_email
else f"Spreadsheet {sheet_id} was not found."
)
try:
import gspread
if isinstance(exc, gspread.exceptions.SpreadsheetNotFound):
return spreadsheet_hint
if isinstance(exc, gspread.exceptions.APIError):
response = exc.response
status_code = getattr(response, "status_code", "unknown")
detail = ""
try:
payload = response.json()
detail = payload.get("error", {}).get("message", "")
except Exception:
detail = getattr(response, "text", "") or str(exc)
if status_code == 404:
return f"HTTP 404 from Google Sheets API. {spreadsheet_hint} Details: {detail}".strip()
return f"Google Sheets API error {status_code}: {detail or exc}"
except Exception:
pass
return f"{type(exc).__name__}: {exc}"
def diagnose_google_sheets() -> dict:
sheet_id = os.getenv("GOOGLE_SHEET_ID", "").strip()
service_account_json = os.getenv("GOOGLE_SERVICE_ACCOUNT_JSON", "").strip()
service_account_file = "google-service-account.json"
if not sheet_id:
return {"ok": False, "reason": "Missing GOOGLE_SHEET_ID"}
if not service_account_json and not os.path.exists(service_account_file):
return {"ok": False, "reason": "Missing GOOGLE_SERVICE_ACCOUNT_JSON and google-service-account.json"}
try:
import gspread
from google.oauth2.service_account import Credentials
scopes = [
'https://www.googleapis.com/auth/spreadsheets',
'https://www.googleapis.com/auth/drive'
]
if service_account_json:
service_account_info = json.loads(service_account_json)
creds = Credentials.from_service_account_info(service_account_info, scopes=scopes)
else:
creds = Credentials.from_service_account_file(service_account_file, scopes=scopes)
client = gspread.authorize(creds)
client.open_by_key(sheet_id).sheet1
return {"ok": True, "reason": ""}
except Exception as exc:
return {"ok": False, "reason": _format_google_sheets_error(exc, sheet_id, service_account_json)}
def _ensure_sheet_headers(sheet) -> None:
current_headers = sheet.row_values(1)
if current_headers[:len(SUMMARY_HEADERS)] == SUMMARY_HEADERS:
return
sheet.update(range_name="A1:N1", values=[SUMMARY_HEADERS])
sheet.format("A1:N1", {
"textFormat": {"bold": True},
"backgroundColor": {"red": 0.9, "green": 0.9, "blue": 0.9},
})
def _write_next_row(sheet, row: list) -> None:
end_column = chr(ord("A") + len(row) - 1)
sheet.append_row(row, value_input_option="RAW", table_range=f"A:{end_column}")
def log_to_google_sheets(
student_name: str,
repo_url: str,
hints_used: int,
score: int,
total_tests: int,
passed_tests: int,
all_passed: bool,
chat_history: list,
submission_record: Optional[dict] = None,
) -> bool:
"""
Log submission to Google Sheets.
Returns True if successful, False otherwise.
If Google Sheets is not configured, returns False silently.
"""
# Check if Google Sheets is configured
sheet_id = os.getenv("GOOGLE_SHEET_ID")
if not sheet_id:
return False # Silently skip if not configured
try:
import gspread
from google.oauth2.service_account import Credentials
# Try to get service account from environment variable first (for cloud deployment)
service_account_json = os.getenv("GOOGLE_SERVICE_ACCOUNT_JSON")
if service_account_json:
# Parse JSON from environment variable
service_account_info = json.loads(service_account_json)
scopes = [
'https://www.googleapis.com/auth/spreadsheets',
'https://www.googleapis.com/auth/drive'
]
creds = Credentials.from_service_account_info(service_account_info, scopes=scopes)
else:
# Fall back to file (for local development)
service_account_file = "google-service-account.json"
if not os.path.exists(service_account_file):
print("โš ๏ธ Google Sheets: service account not configured (neither env var nor file)")
return False
scopes = [
'https://www.googleapis.com/auth/spreadsheets',
'https://www.googleapis.com/auth/drive'
]
creds = Credentials.from_service_account_file(service_account_file, scopes=scopes)
client = gspread.authorize(creds)
# Open the sheet
sheet = client.open_by_key(sheet_id).sheet1
# Initialize or migrate headers to the current schema.
try:
_ensure_sheet_headers(sheet)
except Exception as e:
print(f"โš ๏ธ Could not set headers: {e}")
# Prepare row data
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
# Format chat history nicely
if chat_history:
chat_text = "\n\n".join([
(
f"{'ื”ื™ื ื˜' if msg.get('gave_hint') is True else 'ืฉื™ื—ื”'} #{i+1}:\n"
f"ืฉืืœื”: {msg.get('question') or msg.get('summary', 'N/A')}\n"
f"ืชืฉื•ื‘ื”: {msg.get('response', 'N/A')}"
)
for i, msg in enumerate(chat_history)
])
else:
chat_text = "ืœื ื”ืฉืชืžืฉ ื‘ื”ื™ื ื˜ื™ื"
challenge = submission_record.get("challenge", {}) if submission_record else {}
scoring = submission_record.get("scoring", {}) if submission_record else {}
submission = submission_record.get("submission", {}) if submission_record else {}
student = submission_record.get("student", {}) if submission_record else {}
row = [
timestamp,
student_name or "Anonymous",
challenge.get("challenge_id", ""),
repo_url,
challenge.get("target_file", ""),
score,
hints_used,
f"{passed_tests}/{total_tests}",
"โœ… ื”ืฆืœื™ื—" if all_passed else "โŒ ืœื ื”ืฆืœื™ื—",
scoring.get("submission_outcome", ""),
"ื›ืŸ" if submission.get("touched_bug_function") else "ืœื",
challenge.get("bug_description", ""),
chat_text,
student.get("provider_user_id", ""),
]
# Write deterministically to the next free row.
_write_next_row(sheet, row)
print(f"โœ… Logged to Google Sheets: {student_name} - Score: {score}")
return True
except ImportError:
print("โš ๏ธ Google Sheets: gspread not installed (pip install gspread google-auth)")
return False
except Exception as e:
print(f"โš ๏ธ Google Sheets logging failed: {_format_google_sheets_error(e, sheet_id, service_account_json or '')}")
return False
def initialize_sheet_headers(sheet_id: Optional[str] = None) -> bool:
"""
Initialize Google Sheet with headers if it's empty.
Call this once to set up the sheet.
"""
sheet_id = sheet_id or os.getenv("GOOGLE_SHEET_ID")
if not sheet_id:
print("โŒ GOOGLE_SHEET_ID not set")
return False
try:
import gspread
from google.oauth2.service_account import Credentials
service_account_file = "google-service-account.json"
if not os.path.exists(service_account_file):
print(f"โŒ Service account file not found: {service_account_file}")
return False
scopes = [
'https://www.googleapis.com/auth/spreadsheets',
'https://www.googleapis.com/auth/drive'
]
creds = Credentials.from_service_account_file(service_account_file, scopes=scopes)
client = gspread.authorize(creds)
sheet = client.open_by_key(sheet_id).sheet1
_ensure_sheet_headers(sheet)
print("โœ… Headers initialized!")
return True
except Exception as e:
print(f"โŒ Failed to initialize headers: {e}")
return False
# CLI tool for testing
if __name__ == "__main__":
import sys
if len(sys.argv) > 1 and sys.argv[1] == "init":
# Initialize headers
sheet_id = os.getenv("GOOGLE_SHEET_ID")
if not sheet_id:
print("Set GOOGLE_SHEET_ID in .env first!")
sys.exit(1)
success = initialize_sheet_headers(sheet_id)
sys.exit(0 if success else 1)
else:
# Test logging
print("Testing Google Sheets logging...")
success = log_to_google_sheets(
student_name="Test Student",
repo_url="https://github.com/test/repo",
hints_used=2,
score=85,
total_tests=10,
passed_tests=8,
all_passed=False,
chat_history=[{"role": "user", "content": "test"}],
)
if success:
print("โœ… Test successful!")
else:
print("โŒ Test failed - check configuration")