Spaces:
Sleeping
Sleeping
github-actions[bot] commited on
Commit ·
a187357
1
Parent(s): 084819e
deploy: backend from d4b2808
Browse files- config/env.sample +2 -0
- rag/curriculum_rag.py +18 -1
- rag/firebase_storage_loader.py +114 -42
- routes/admin_routes.py +30 -14
- scripts/download_vectorstore_from_firebase.py +18 -2
- scripts/ingest_from_storage.py +27 -15
- scripts/upload_vectorstore_to_firebase.py +31 -9
- startup.sh +5 -5
config/env.sample
CHANGED
|
@@ -48,6 +48,8 @@ INFERENCE_BACKGROUND_TIMEOUT_SEC=120
|
|
| 48 |
CURRICULUM_SOURCE_REPO_ID=Deign86/mathpulse-curriculum
|
| 49 |
CURRICULUM_SOURCE_REPO_TYPE=dataset
|
| 50 |
CURRICULUM_SOURCE_REVISION=main
|
|
|
|
|
|
|
| 51 |
|
| 52 |
# Transactional email settings for admin-created accounts
|
| 53 |
# Primary provider: Brevo Transactional API
|
|
|
|
| 48 |
CURRICULUM_SOURCE_REPO_ID=Deign86/mathpulse-curriculum
|
| 49 |
CURRICULUM_SOURCE_REPO_TYPE=dataset
|
| 50 |
CURRICULUM_SOURCE_REVISION=main
|
| 51 |
+
CURRICULUM_VECTORSTORE_DIR=datasets/vectorstore
|
| 52 |
+
EMBEDDING_MODEL=BAAI/bge-small-en-v1.5
|
| 53 |
|
| 54 |
# Transactional email settings for admin-created accounts
|
| 55 |
# Primary provider: Brevo Transactional API
|
rag/curriculum_rag.py
CHANGED
|
@@ -7,6 +7,19 @@ from __future__ import annotations
|
|
| 7 |
from typing import Any, Dict, List, Optional, Tuple
|
| 8 |
|
| 9 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
def _to_where(
|
| 11 |
subject: Optional[str] = None,
|
| 12 |
quarter: Optional[int] = None,
|
|
@@ -19,7 +32,11 @@ def _to_where(
|
|
| 19 |
) -> Optional[Dict[str, object]]:
|
| 20 |
clauses = []
|
| 21 |
if subject:
|
| 22 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
if quarter is not None:
|
| 24 |
clauses.append({"quarter": {"$eq": int(quarter)}})
|
| 25 |
if content_domain:
|
|
|
|
| 7 |
from typing import Any, Dict, List, Optional, Tuple
|
| 8 |
|
| 9 |
|
| 10 |
+
def _normalize_subject(subject: Optional[str]) -> Optional[str]:
|
| 11 |
+
if not subject:
|
| 12 |
+
return None
|
| 13 |
+
raw = subject.strip().lower().replace("-", "_").replace(" ", "_")
|
| 14 |
+
if "gen" in raw or "general" in raw:
|
| 15 |
+
return "general_mathematics"
|
| 16 |
+
if "finite" in raw and "1" in raw:
|
| 17 |
+
return "finite_mathematics_1"
|
| 18 |
+
if "finite" in raw and "2" in raw:
|
| 19 |
+
return "finite_mathematics_2"
|
| 20 |
+
return raw
|
| 21 |
+
|
| 22 |
+
|
| 23 |
def _to_where(
|
| 24 |
subject: Optional[str] = None,
|
| 25 |
quarter: Optional[int] = None,
|
|
|
|
| 32 |
) -> Optional[Dict[str, object]]:
|
| 33 |
clauses = []
|
| 34 |
if subject:
|
| 35 |
+
norm = _normalize_subject(subject)
|
| 36 |
+
if norm and norm != subject:
|
| 37 |
+
clauses.append({"subject": {"$in": [subject, norm]}})
|
| 38 |
+
else:
|
| 39 |
+
clauses.append({"subject": {"$eq": subject}})
|
| 40 |
if quarter is not None:
|
| 41 |
clauses.append({"quarter": {"$eq": int(quarter)}})
|
| 42 |
if content_domain:
|
rag/firebase_storage_loader.py
CHANGED
|
@@ -67,58 +67,130 @@ def _init_firebase_storage() -> Tuple[any, any]:
|
|
| 67 |
|
| 68 |
|
| 69 |
def download_pdf_from_storage(storage_path: str, dest_path: Optional[str] = None) -> Optional[bytes]:
|
| 70 |
-
"""Download a PDF from Firebase Storage and return its bytes."""
|
| 71 |
_, bucket = _init_firebase_storage()
|
| 72 |
-
if bucket is None:
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
logger.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
return None
|
| 81 |
-
bytes_data = blob.download_as_bytes()
|
| 82 |
-
logger.info("Downloaded %s (%d bytes)", storage_path, len(bytes_data))
|
| 83 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 84 |
if dest_path:
|
| 85 |
Path(dest_path).parent.mkdir(parents=True, exist_ok=True)
|
| 86 |
with open(dest_path, "wb") as f:
|
| 87 |
-
f.write(
|
| 88 |
-
|
|
|
|
|
|
|
| 89 |
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
logger.error("Failed to download %s: %s", storage_path, e)
|
| 93 |
-
return None
|
| 94 |
|
| 95 |
|
| 96 |
-
def list_curriculum_blobs(prefix: str = "curriculum/") -> List[Dict[str,
|
| 97 |
-
"""List all blobs under a prefix in Firebase Storage."""
|
| 98 |
_, bucket = _init_firebase_storage()
|
| 99 |
-
if bucket is None:
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 122 |
|
| 123 |
PDF_METADATA: Dict[str, dict] = {
|
| 124 |
# General Mathematics Q1 — SDO Navotas teaching module (100 pages, ~117k chars)
|
|
|
|
| 67 |
|
| 68 |
|
| 69 |
def download_pdf_from_storage(storage_path: str, dest_path: Optional[str] = None) -> Optional[bytes]:
|
| 70 |
+
"""Download a file (PDF or Markdown) from Firebase Storage and return its bytes."""
|
| 71 |
_, bucket = _init_firebase_storage()
|
| 72 |
+
if bucket is not None:
|
| 73 |
+
try:
|
| 74 |
+
blob = bucket.blob(storage_path)
|
| 75 |
+
if not blob.exists():
|
| 76 |
+
logger.warning("Blob does not exist: %s", storage_path)
|
| 77 |
+
return None
|
| 78 |
+
bytes_data = blob.download_as_bytes()
|
| 79 |
+
logger.info("Downloaded %s (%d bytes)", storage_path, len(bytes_data))
|
| 80 |
+
|
| 81 |
+
if dest_path:
|
| 82 |
+
Path(dest_path).parent.mkdir(parents=True, exist_ok=True)
|
| 83 |
+
with open(dest_path, "wb") as f:
|
| 84 |
+
f.write(bytes_data)
|
| 85 |
+
logger.info("Saved to %s", dest_path)
|
| 86 |
+
|
| 87 |
+
return bytes_data
|
| 88 |
+
except Exception as e:
|
| 89 |
+
logger.error("Failed to download %s: %s", storage_path, e)
|
| 90 |
return None
|
|
|
|
|
|
|
| 91 |
|
| 92 |
+
# Fallback to gcloud storage cat
|
| 93 |
+
import shutil
|
| 94 |
+
import subprocess
|
| 95 |
+
|
| 96 |
+
gcloud_bin = shutil.which("gcloud") or "gcloud"
|
| 97 |
+
bucket_name = os.getenv("FIREBASE_STORAGE_BUCKET", "mathpulse-ai-2026.firebasestorage.app")
|
| 98 |
+
cmd = f'"{gcloud_bin}" storage cat "gs://{bucket_name}/{storage_path}"'
|
| 99 |
+
res = subprocess.run(cmd, shell=True, capture_output=True)
|
| 100 |
+
if res.returncode == 0 and res.stdout:
|
| 101 |
+
logger.info("Downloaded via gcloud %s (%d bytes)", storage_path, len(res.stdout))
|
| 102 |
if dest_path:
|
| 103 |
Path(dest_path).parent.mkdir(parents=True, exist_ok=True)
|
| 104 |
with open(dest_path, "wb") as f:
|
| 105 |
+
f.write(res.stdout)
|
| 106 |
+
return res.stdout
|
| 107 |
+
logger.warning("Download failed for %s", storage_path)
|
| 108 |
+
return None
|
| 109 |
|
| 110 |
+
|
| 111 |
+
download_file_from_storage = download_pdf_from_storage
|
|
|
|
|
|
|
| 112 |
|
| 113 |
|
| 114 |
+
def list_curriculum_blobs(prefix: str = "curriculum/") -> List[Dict[str, Any]]:
|
| 115 |
+
"""List all curriculum blobs (PDF and Markdown) under a prefix in Firebase Storage."""
|
| 116 |
_, bucket = _init_firebase_storage()
|
| 117 |
+
if bucket is not None:
|
| 118 |
+
blobs = bucket.list_blobs(prefix=prefix)
|
| 119 |
+
result = []
|
| 120 |
+
for blob in blobs:
|
| 121 |
+
name = blob.name
|
| 122 |
+
if (name.endswith(".pdf") or name.endswith(".md")) and not name.lower().endswith("readme.md"):
|
| 123 |
+
result.append({
|
| 124 |
+
"name": name,
|
| 125 |
+
"size": blob.size,
|
| 126 |
+
"updated": str(blob.updated) if blob.updated else None,
|
| 127 |
+
"download_url": f"https://storage.googleapis.com/{bucket.name}/{name}",
|
| 128 |
+
})
|
| 129 |
+
return result
|
| 130 |
+
|
| 131 |
+
# Fallback to gcloud storage ls
|
| 132 |
+
import json
|
| 133 |
+
import shutil
|
| 134 |
+
import subprocess
|
| 135 |
+
|
| 136 |
+
gcloud_bin = shutil.which("gcloud") or "gcloud"
|
| 137 |
+
bucket_name = os.getenv("FIREBASE_STORAGE_BUCKET", "mathpulse-ai-2026.firebasestorage.app")
|
| 138 |
+
cmd = f'"{gcloud_bin}" storage ls --json "gs://{bucket_name}/{prefix}**"'
|
| 139 |
+
res = subprocess.run(cmd, shell=True, capture_output=True, text=True)
|
| 140 |
+
if res.returncode == 0:
|
| 141 |
+
try:
|
| 142 |
+
items = json.loads(res.stdout)
|
| 143 |
+
result = []
|
| 144 |
+
for item in items:
|
| 145 |
+
meta = item.get("metadata", {})
|
| 146 |
+
name = meta.get("name") or item.get("name") or ""
|
| 147 |
+
if (name.endswith(".pdf") or name.endswith(".md")) and not name.lower().endswith("readme.md"):
|
| 148 |
+
result.append({
|
| 149 |
+
"name": name,
|
| 150 |
+
"size": int(meta.get("size", 0)),
|
| 151 |
+
"updated": meta.get("updated"),
|
| 152 |
+
"download_url": f"https://storage.googleapis.com/{bucket_name}/{name}",
|
| 153 |
+
})
|
| 154 |
+
return result
|
| 155 |
+
except Exception as err:
|
| 156 |
+
logger.warning("Failed to parse gcloud storage ls output: %s", err)
|
| 157 |
+
return []
|
| 158 |
+
return []
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def infer_storage_metadata(storage_path: str) -> Dict[str, Any]:
|
| 162 |
+
"""Infer metadata for a curriculum resource stored in Firebase Storage."""
|
| 163 |
+
clean_path = storage_path.replace("\\", "/")
|
| 164 |
+
parts = [p.lower() for p in clean_path.split("/")]
|
| 165 |
+
joined = " ".join(parts)
|
| 166 |
+
filename = parts[-1] if parts else ""
|
| 167 |
+
|
| 168 |
+
subject = "Finite Mathematics" if "finite math" in joined else "General Mathematics"
|
| 169 |
+
subject_id = "finite-math" if "finite math" in joined else "gen-math"
|
| 170 |
+
quarter = 0
|
| 171 |
+
for q in [1, 2, 3, 4]:
|
| 172 |
+
if f"q{q}" in joined or f"quarter {q}" in joined:
|
| 173 |
+
quarter = q
|
| 174 |
+
break
|
| 175 |
+
|
| 176 |
+
resource_type = "sdo_module"
|
| 177 |
+
if "las" in filename:
|
| 178 |
+
resource_type = "learning_activity_sheet"
|
| 179 |
+
elif "le" in filename:
|
| 180 |
+
resource_type = "lesson_exemplar"
|
| 181 |
+
elif "curriculum" in filename:
|
| 182 |
+
resource_type = "curriculum_guide"
|
| 183 |
+
|
| 184 |
+
return {
|
| 185 |
+
"subject": subject,
|
| 186 |
+
"subjectId": subject_id,
|
| 187 |
+
"type": resource_type,
|
| 188 |
+
"content_domain": "general",
|
| 189 |
+
"quarter": quarter,
|
| 190 |
+
"storage_path": clean_path,
|
| 191 |
+
"filename": filename,
|
| 192 |
+
}
|
| 193 |
+
|
| 194 |
|
| 195 |
PDF_METADATA: Dict[str, dict] = {
|
| 196 |
# General Mathematics Q1 — SDO Navotas teaching module (100 pages, ~117k chars)
|
routes/admin_routes.py
CHANGED
|
@@ -102,28 +102,44 @@ async def upload_pdf(
|
|
| 102 |
"storageUrl": storage_url
|
| 103 |
}
|
| 104 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 105 |
@router.post("/reingest-pdf")
|
| 106 |
async def reingest_pdf(
|
|
|
|
| 107 |
req: Optional[ReingestRequest] = None,
|
| 108 |
_admin=Depends(require_admin)
|
| 109 |
):
|
| 110 |
try:
|
| 111 |
-
|
| 112 |
import asyncio
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
|
|
|
|
|
|
| 124 |
except Exception as e:
|
| 125 |
-
logger.error(f"Failed to
|
| 126 |
-
raise HTTPException(status_code=500, detail=f"Failed to
|
| 127 |
|
| 128 |
|
| 129 |
class DeleteFileRequest(BaseModel):
|
|
|
|
| 102 |
"storageUrl": storage_url
|
| 103 |
}
|
| 104 |
|
| 105 |
+
def _run_reingestion_task():
|
| 106 |
+
try:
|
| 107 |
+
logger.info("Starting background curriculum reingestion from Firebase Storage...")
|
| 108 |
+
ingest_from_firebase_storage(force_reindex=True)
|
| 109 |
+
from scripts.upload_vectorstore_to_firebase import upload_directory, _init_firebase_storage, VECTORSTORE_SOURCE_DIR, REMOTE_PREFIX
|
| 110 |
+
_, bucket = _init_firebase_storage()
|
| 111 |
+
if bucket is not None:
|
| 112 |
+
upload_directory(VECTORSTORE_SOURCE_DIR, bucket, REMOTE_PREFIX)
|
| 113 |
+
logger.info("Background curriculum reingestion complete.")
|
| 114 |
+
except Exception as exc:
|
| 115 |
+
logger.error(f"Background reingestion failed: {exc}")
|
| 116 |
+
|
| 117 |
+
|
| 118 |
@router.post("/reingest-pdf")
|
| 119 |
async def reingest_pdf(
|
| 120 |
+
background_tasks: BackgroundTasks,
|
| 121 |
req: Optional[ReingestRequest] = None,
|
| 122 |
_admin=Depends(require_admin)
|
| 123 |
):
|
| 124 |
try:
|
| 125 |
+
background_tasks.add_task(_run_reingestion_task)
|
| 126 |
import asyncio
|
| 127 |
+
audit_fn = _get_audit_logger()
|
| 128 |
+
if audit_fn:
|
| 129 |
+
asyncio.create_task(audit_fn(
|
| 130 |
+
action="REINGEST_RAG_KNOWLEDGE",
|
| 131 |
+
actor_uid=_admin.uid,
|
| 132 |
+
actor_name=_admin.name if hasattr(_admin, "name") else "Unknown",
|
| 133 |
+
actor_email=_admin.email if hasattr(_admin, "email") else "",
|
| 134 |
+
actor_role=_admin.role,
|
| 135 |
+
description="Triggered remote cloud reingestion of the RAG knowledge base in background",
|
| 136 |
+
route="/api/admin/reingest-pdf",
|
| 137 |
+
module="admin"
|
| 138 |
+
))
|
| 139 |
+
return {"success": True, "message": "Remote re-ingestion started in background. Check RAG Manager in a few minutes."}
|
| 140 |
except Exception as e:
|
| 141 |
+
logger.error(f"Failed to trigger reingestion: {e}")
|
| 142 |
+
raise HTTPException(status_code=500, detail=f"Failed to trigger reingestion: {e}")
|
| 143 |
|
| 144 |
|
| 145 |
class DeleteFileRequest(BaseModel):
|
scripts/download_vectorstore_from_firebase.py
CHANGED
|
@@ -71,11 +71,27 @@ def _resolve_dest_dir() -> Path:
|
|
| 71 |
return Path("/app/datasets/vectorstore")
|
| 72 |
|
| 73 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
def download_vectorstore(dest_dir: Path, prefix: str = REMOTE_PREFIX):
|
| 75 |
bucket = _init_firebase()
|
| 76 |
if bucket is None:
|
| 77 |
-
|
| 78 |
-
|
|
|
|
| 79 |
|
| 80 |
dest_dir.mkdir(parents=True, exist_ok=True)
|
| 81 |
|
|
|
|
| 71 |
return Path("/app/datasets/vectorstore")
|
| 72 |
|
| 73 |
|
| 74 |
+
def download_via_gcloud(dest_dir: Path, bucket_name: str, prefix: str = REMOTE_PREFIX) -> bool:
|
| 75 |
+
import shutil
|
| 76 |
+
import subprocess
|
| 77 |
+
gcloud_bin = shutil.which("gcloud") or "gcloud"
|
| 78 |
+
src_uri = f"gs://{bucket_name}/{prefix}"
|
| 79 |
+
logger.info("Executing gcloud storage rsync from %s to %s", src_uri, dest_dir)
|
| 80 |
+
cmd = f'"{gcloud_bin}" storage rsync -r "{src_uri}" "{dest_dir}"'
|
| 81 |
+
res = subprocess.run(cmd, shell=True, capture_output=True, text=True)
|
| 82 |
+
if res.returncode == 0:
|
| 83 |
+
logger.info("gcloud storage download succeeded:\n%s", res.stdout)
|
| 84 |
+
return True
|
| 85 |
+
logger.error("gcloud storage download failed:\n%s\n%s", res.stdout, res.stderr)
|
| 86 |
+
return False
|
| 87 |
+
|
| 88 |
+
|
| 89 |
def download_vectorstore(dest_dir: Path, prefix: str = REMOTE_PREFIX):
|
| 90 |
bucket = _init_firebase()
|
| 91 |
if bucket is None:
|
| 92 |
+
bucket_name = os.getenv("FIREBASE_STORAGE_BUCKET", "mathpulse-ai-2026.firebasestorage.app")
|
| 93 |
+
logger.info("Firebase admin unavailable; attempting gcloud storage fallback...")
|
| 94 |
+
return download_via_gcloud(dest_dir, bucket_name, prefix)
|
| 95 |
|
| 96 |
dest_dir.mkdir(parents=True, exist_ok=True)
|
| 97 |
|
scripts/ingest_from_storage.py
CHANGED
|
@@ -18,6 +18,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
|
|
| 18 |
from rag.firebase_storage_loader import (
|
| 19 |
PDF_METADATA,
|
| 20 |
download_pdf_from_storage,
|
|
|
|
| 21 |
list_curriculum_blobs,
|
| 22 |
)
|
| 23 |
|
|
@@ -149,8 +150,21 @@ def ingest_from_firebase_storage(force_reindex: bool = False):
|
|
| 149 |
skipped_count = 0
|
| 150 |
error_count = 0
|
| 151 |
|
| 152 |
-
|
| 153 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 154 |
|
| 155 |
if db:
|
| 156 |
try:
|
|
@@ -167,22 +181,20 @@ def ingest_from_firebase_storage(force_reindex: bool = False):
|
|
| 167 |
logger.info("Downloading: %s", storage_path)
|
| 168 |
pdf_bytes = download_pdf_from_storage(storage_path)
|
| 169 |
if pdf_bytes is None:
|
| 170 |
-
logger.
|
| 171 |
-
|
| 172 |
-
try:
|
| 173 |
-
doc_ref.set({
|
| 174 |
-
"storagePath": storage_path,
|
| 175 |
-
"status": "failed",
|
| 176 |
-
"error": "download_failed",
|
| 177 |
-
**metadata,
|
| 178 |
-
}, merge=True)
|
| 179 |
-
except:
|
| 180 |
-
pass
|
| 181 |
-
error_count += 1
|
| 182 |
continue
|
| 183 |
|
| 184 |
logger.info("Extracting text from: %s (%d bytes)", storage_path, len(pdf_bytes))
|
| 185 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 186 |
if not full_text.strip():
|
| 187 |
logger.warning("[WARN] No text extracted from: %s", storage_path)
|
| 188 |
error_count += 1
|
|
|
|
| 18 |
from rag.firebase_storage_loader import (
|
| 19 |
PDF_METADATA,
|
| 20 |
download_pdf_from_storage,
|
| 21 |
+
infer_storage_metadata,
|
| 22 |
list_curriculum_blobs,
|
| 23 |
)
|
| 24 |
|
|
|
|
| 150 |
skipped_count = 0
|
| 151 |
error_count = 0
|
| 152 |
|
| 153 |
+
target_metadata: Dict[str, Any] = {}
|
| 154 |
+
live_blobs = list_curriculum_blobs(prefix="curriculum/sshs_learning_resources/")
|
| 155 |
+
md_stems = {
|
| 156 |
+
blob["name"].rsplit("/", 1)[-1].lower().replace(".md", "")
|
| 157 |
+
for blob in live_blobs if blob["name"].endswith(".md")
|
| 158 |
+
}
|
| 159 |
+
for blob_info in live_blobs:
|
| 160 |
+
path = blob_info["name"]
|
| 161 |
+
stem = path.rsplit("/", 1)[-1].lower().replace(".pdf", "").replace(".md", "")
|
| 162 |
+
if path.endswith(".pdf") and stem in md_stems:
|
| 163 |
+
continue
|
| 164 |
+
target_metadata[path] = infer_storage_metadata(path)
|
| 165 |
+
|
| 166 |
+
for storage_path, metadata in target_metadata.items():
|
| 167 |
+
doc_id = storage_path.replace("/", "_").replace(".pdf", "").replace(".md", "")
|
| 168 |
|
| 169 |
if db:
|
| 170 |
try:
|
|
|
|
| 181 |
logger.info("Downloading: %s", storage_path)
|
| 182 |
pdf_bytes = download_pdf_from_storage(storage_path)
|
| 183 |
if pdf_bytes is None:
|
| 184 |
+
logger.warning("[SKIP] %s not found in Firebase Storage", storage_path)
|
| 185 |
+
skipped_count += 1
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 186 |
continue
|
| 187 |
|
| 188 |
logger.info("Extracting text from: %s (%d bytes)", storage_path, len(pdf_bytes))
|
| 189 |
+
if storage_path.endswith(".md"):
|
| 190 |
+
try:
|
| 191 |
+
full_text = pdf_bytes.decode("utf-8")
|
| 192 |
+
except UnicodeDecodeError:
|
| 193 |
+
full_text = pdf_bytes.decode("utf-8", errors="ignore")
|
| 194 |
+
page_starts = [0]
|
| 195 |
+
else:
|
| 196 |
+
full_text, page_starts = extract_pdf_text_and_pages(pdf_bytes)
|
| 197 |
+
|
| 198 |
if not full_text.strip():
|
| 199 |
logger.warning("[WARN] No text extracted from: %s", storage_path)
|
| 200 |
error_count += 1
|
scripts/upload_vectorstore_to_firebase.py
CHANGED
|
@@ -16,7 +16,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
|
|
| 16 |
|
| 17 |
from backend.rag.firebase_storage_loader import _init_firebase_storage
|
| 18 |
|
| 19 |
-
VECTORSTORE_SOURCE_DIR = Path(__file__).resolve().parents[
|
| 20 |
REMOTE_PREFIX = "vectorstore/"
|
| 21 |
|
| 22 |
|
|
@@ -27,6 +27,8 @@ def upload_directory(local_dir: Path, bucket, prefix: str):
|
|
| 27 |
|
| 28 |
for root, dirs, files in os.walk(local_dir):
|
| 29 |
for filename in files:
|
|
|
|
|
|
|
| 30 |
local_path = Path(root) / filename
|
| 31 |
relative_path = local_path.relative_to(local_dir)
|
| 32 |
remote_path = f"{prefix}{relative_path.as_posix()}"
|
|
@@ -43,6 +45,23 @@ def upload_directory(local_dir: Path, bucket, prefix: str):
|
|
| 43 |
return uploaded, skipped
|
| 44 |
|
| 45 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
if __name__ == "__main__":
|
| 47 |
import argparse
|
| 48 |
|
|
@@ -60,12 +79,15 @@ if __name__ == "__main__":
|
|
| 60 |
logger.error("Source directory does not exist: %s", source_dir)
|
| 61 |
sys.exit(1)
|
| 62 |
|
|
|
|
| 63 |
_, bucket = _init_firebase_storage()
|
| 64 |
-
if bucket is None:
|
| 65 |
-
logger.
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
from backend.rag.firebase_storage_loader import _init_firebase_storage
|
| 18 |
|
| 19 |
+
VECTORSTORE_SOURCE_DIR = Path(__file__).resolve().parents[2] / "datasets" / "vectorstore"
|
| 20 |
REMOTE_PREFIX = "vectorstore/"
|
| 21 |
|
| 22 |
|
|
|
|
| 27 |
|
| 28 |
for root, dirs, files in os.walk(local_dir):
|
| 29 |
for filename in files:
|
| 30 |
+
if filename.endswith(".npy"):
|
| 31 |
+
continue
|
| 32 |
local_path = Path(root) / filename
|
| 33 |
relative_path = local_path.relative_to(local_dir)
|
| 34 |
remote_path = f"{prefix}{relative_path.as_posix()}"
|
|
|
|
| 45 |
return uploaded, skipped
|
| 46 |
|
| 47 |
|
| 48 |
+
def upload_via_gcloud(source_dir: Path, bucket_name: str, prefix: str):
|
| 49 |
+
"""Fallback upload using gcloud storage CLI."""
|
| 50 |
+
import subprocess
|
| 51 |
+
import shutil
|
| 52 |
+
|
| 53 |
+
gcloud_bin = shutil.which("gcloud") or "gcloud"
|
| 54 |
+
dest_uri = f"gs://{bucket_name}/{prefix}"
|
| 55 |
+
logger.info("Executing gcloud storage rsync from %s to %s", source_dir, dest_uri)
|
| 56 |
+
cmd = f'"{gcloud_bin}" storage rsync -r "{source_dir}" "{dest_uri}"'
|
| 57 |
+
res = subprocess.run(cmd, shell=True, capture_output=True, text=True)
|
| 58 |
+
if res.returncode == 0:
|
| 59 |
+
logger.info("gcloud storage upload succeeded:\n%s", res.stdout)
|
| 60 |
+
return True
|
| 61 |
+
logger.error("gcloud storage upload failed:\n%s\n%s", res.stdout, res.stderr)
|
| 62 |
+
return False
|
| 63 |
+
|
| 64 |
+
|
| 65 |
if __name__ == "__main__":
|
| 66 |
import argparse
|
| 67 |
|
|
|
|
| 79 |
logger.error("Source directory does not exist: %s", source_dir)
|
| 80 |
sys.exit(1)
|
| 81 |
|
| 82 |
+
bucket_name = os.getenv("FIREBASE_STORAGE_BUCKET", "mathpulse-ai-2026.firebasestorage.app")
|
| 83 |
_, bucket = _init_firebase_storage()
|
| 84 |
+
if bucket is not None:
|
| 85 |
+
logger.info("Uploading vectorstore from %s to gs://%s/%s via firebase-admin",
|
| 86 |
+
source_dir, bucket.name, args.prefix)
|
| 87 |
+
uploaded, skipped = upload_directory(source_dir, bucket, args.prefix)
|
| 88 |
+
logger.info("Upload complete: %d uploaded, %d skipped", uploaded, skipped)
|
| 89 |
+
else:
|
| 90 |
+
logger.info("firebase_admin bucket not available; attempting gcloud storage fallback...")
|
| 91 |
+
success = upload_via_gcloud(source_dir, bucket_name, args.prefix)
|
| 92 |
+
if not success:
|
| 93 |
+
sys.exit(1)
|
startup.sh
CHANGED
|
@@ -33,15 +33,15 @@ fi
|
|
| 33 |
|
| 34 |
_ingest_script="/app/scripts/ingest_curriculum.py"
|
| 35 |
if [ -f "${_ingest_script}" ]; then
|
| 36 |
-
|
| 37 |
-
if [ -d "${CURRICULUM_DIR}" ] && find "${CURRICULUM_DIR}" -type f -name '*.pdf' -print -quit >/dev/null 2>&1; then
|
| 38 |
-
|
| 39 |
fi
|
| 40 |
-
if [ "${
|
| 41 |
echo "INFO: Running curriculum ingestion (optional)..."
|
| 42 |
python "${_ingest_script}" && echo "INFO: Curriculum ingestion completed" || echo "WARNING: Curriculum ingestion failed, continuing anyway"
|
| 43 |
else
|
| 44 |
-
echo "INFO: No curriculum
|
| 45 |
fi
|
| 46 |
else
|
| 47 |
echo "INFO: Curriculum ingestion script not found at ${_ingest_script}; skipping (curriculum is optional)"
|
|
|
|
| 33 |
|
| 34 |
_ingest_script="/app/scripts/ingest_curriculum.py"
|
| 35 |
if [ -f "${_ingest_script}" ]; then
|
| 36 |
+
_has_curriculum_files=false
|
| 37 |
+
if [ -d "${CURRICULUM_DIR}" ] && (find "${CURRICULUM_DIR}" -type f \( -name '*.pdf' -o -name '*.md' \) ! -name 'README.md' -print -quit >/dev/null 2>&1); then
|
| 38 |
+
_has_curriculum_files=true
|
| 39 |
fi
|
| 40 |
+
if [ "${_has_curriculum_files}" = true ] || [ -n "${CURRICULUM_SOURCE_REPO_ID:-}" ]; then
|
| 41 |
echo "INFO: Running curriculum ingestion (optional)..."
|
| 42 |
python "${_ingest_script}" && echo "INFO: Curriculum ingestion completed" || echo "WARNING: Curriculum ingestion failed, continuing anyway"
|
| 43 |
else
|
| 44 |
+
echo "INFO: No curriculum files present and CURRICULUM_SOURCE_REPO_ID unset; skipping ingest"
|
| 45 |
fi
|
| 46 |
else
|
| 47 |
echo "INFO: Curriculum ingestion script not found at ${_ingest_script}; skipping (curriculum is optional)"
|