Spaces:
Sleeping
Sleeping
Harden submission logger paths and sheet diagnostics
Browse filesFiles changed (2)
14 unmodified lines15161718192017 unmodified lines383940414243152 unmodified lines19619719819920020120220320420520614 unmodified linesimport osimport jsonimport subprocessfrom datetime import datetimefrom pathlib import Pathfrom typing import Optional17 unmodified linesreturn repo_url.replace("https://", f"https://{git_token}@", 1)def diagnose_git_submissions() -> dict:submissions_repo = os.getenv("SUBMISSIONS_REPO_URL", "").strip()git_token = os.getenv("SUBMISSIONS_GIT_TOKEN", "").strip()152 unmodified lines# Create submission folder nametimestamp = datetime.now().strftime("%Y-%m-%d_%H%M")repo_name = repo_url.split('/')[-1].replace('.git', '')folder_name = f"{timestamp}_{student_name}_{repo_name}"submission_folder = submissions_dir / folder_namesubmission_folder.mkdir(exist_ok=True)print(f"📁 Creating submission: {folder_name}")# Prepare files to write14 unmodified lines1516171819202117 unmodified lines39404142434445464748495051525354152 unmodified lines20720820921021121221321421521621721814 unmodified linesimport osimport jsonimport subprocessimport refrom datetime import datetimefrom pathlib import Pathfrom typing import Optional17 unmodified linesreturn repo_url.replace("https://", f"https://{git_token}@", 1)def _safe_path_component(value: str, fallback: str) -> str:value = (value or "").strip()if not value:return fallbackvalue = value.replace("\\", "_").replace("/", "_")value = re.sub(r'[<>:"|?*\x00-\x1f]', "_", value)value = re.sub(r'\s+', " ", value).strip(" .")return value or fallbackdef diagnose_git_submissions() -> dict:submissions_repo = os.getenv("SUBMISSIONS_REPO_URL", "").strip()git_token = os.getenv("SUBMISSIONS_GIT_TOKEN", "").strip()152 unmodified lines# Create submission folder nametimestamp = datetime.now().strftime("%Y-%m-%d_%H%M")repo_name = _safe_path_component(repo_url.split('/')[-1].replace('.git', ''), "repo")safe_student_name = _safe_path_component(student_name, "anonymous")folder_name = f"{timestamp}_{safe_student_name}_{repo_name}"submission_folder = submissions_dir / folder_namesubmission_folder.mkdir(parents=True, exist_ok=True)print(f"📁 Creating submission: {folder_name}")# Prepare files to write
5 unmodified lines6789101120 unmodified lines3233343536376 unmodified lines4445464748495010 unmodified lines6162636465666742 unmodified lines11011111211311411511673 unmodified lines1901911921931941951965 unmodified lines"""import osfrom datetime import datetimefrom typing import Optional20 unmodified lines]def diagnose_google_sheets() -> dict:sheet_id = os.getenv("GOOGLE_SHEET_ID", "").strip()service_account_json = os.getenv("GOOGLE_SERVICE_ACCOUNT_JSON", "").strip()6 unmodified linestry:import gspreadimport jsonfrom google.oauth2.service_account import Credentialsscopes = [10 unmodified linesclient.open_by_key(sheet_id).sheet1return {"ok": True, "reason": ""}except Exception as exc:return {"ok": False, "reason": f"{type(exc).__name__}: {exc}"}def _ensure_sheet_headers(sheet) -> None:42 unmodified linestry:import gspreadimport jsonfrom google.oauth2.service_account import Credentials# Try to get service account from environment variable first (for cloud deployment)73 unmodified linesprint("⚠️ Google Sheets: gspread not installed (pip install gspread google-auth)")return Falseexcept Exception as e:print(f"⚠️ Google Sheets logging failed: {e}")return False5 unmodified lines678910111220 unmodified lines33343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778796 unmodified lines86878889909110 unmodified lines10210310410510610710842 unmodified lines15115215315415515673 unmodified lines2302312322332342352365 unmodified lines"""import osimport jsonfrom datetime import datetimefrom typing import Optional20 unmodified lines]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_emailelse f"Spreadsheet {sheet_id} was not found.")try:import gspreadif isinstance(exc, gspread.exceptions.SpreadsheetNotFound):return spreadsheet_hintif isinstance(exc, gspread.exceptions.APIError):response = exc.responsestatus_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:passreturn 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()6 unmodified linestry:import gspreadfrom google.oauth2.service_account import Credentialsscopes = [10 unmodified linesclient.open_by_key(sheet_id).sheet1return {"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:42 unmodified linestry:import gspreadfrom google.oauth2.service_account import Credentials# Try to get service account from environment variable first (for cloud deployment)73 unmodified linesprint("⚠️ Google Sheets: gspread not installed (pip install gspread google-auth)")return Falseexcept Exception as e:print(f"⚠️ Google Sheets logging failed: {_format_google_sheets_error(e, sheet_id, service_account_json or '')}")return False
git_submissions_logger.py+15-3
google_sheets_logger.py+44-4