Spaces:
Sleeping
Sleeping
File size: 2,945 Bytes
618e9ca 9386ce8 acf837b c1dfa67 6d6636b c1dfa67 618e9ca c1dfa67 9785201 c1dfa67 9785201 c1dfa67 9785201 6d6636b c1dfa67 6d6636b c1dfa67 b0077fd 6d6636b c1dfa67 92f1cfa d6fcb7e 92f1cfa c1dfa67 d6fcb7e c1dfa67 92f1cfa c1dfa67 |
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 |
# app/db.py
from motor.motor_asyncio import AsyncIOMotorClient, AsyncIOMotorGridFSBucket
from pymongo.uri_parser import parse_uri
import os, logging
logger = logging.getLogger("book-query")
MONGO_URI = os.getenv("MONGODB_URI")
MONGO_DB_NAME = os.getenv("MONGODB_DB", "querysearcher")
TEXTBOOK_URI = os.getenv("TEXTBOOK_URI")
# ────────────────────────────────────────────────────────────────
# helpers for the main “query-searcher” DB
# ────────────────────────────────────────────────────────────────
def get_client():
return AsyncIOMotorClient(MONGO_URI)
def get_db():
return get_client()[MONGO_DB_NAME]
def get_gridfs():
return AsyncIOMotorGridFSBucket(get_db())
# ────────────────────────────────────────────────────────────────
# ONE canonical helper for the *textbook* bucket
# ────────────────────────────────────────────────────────────────
def _get_textbook_fs() -> AsyncIOMotorGridFSBucket:
"""
Build (and cache) a GridFS bucket that points to the textbook replica.
Works whether TEXTBOOK_URI ends with '/<db>' or not.
"""
if not TEXTBOOK_URI:
raise RuntimeError("TEXTBOOK_URI not set in environment")
parsed = parse_uri(TEXTBOOK_URI)
db_name = parsed.get("database") or "textbooks" # fallback name
client = AsyncIOMotorClient(TEXTBOOK_URI)
return AsyncIOMotorGridFSBucket(client[db_name])
# ── public wrappers ─────────────────────────────────────────────
async def save_to_textbook_fs(doc_id: str, file_path: str):
try:
bucket = _get_textbook_fs()
with open(file_path, "rb") as fp:
await bucket.upload_from_stream(f"{doc_id}.pdf", fp)
logger.info(f"📦 textbook PDF stored for {doc_id} → {TEXTBOOK_URI}")
except Exception as e:
logger.warning(f"⚠️ textbook GridFS save failed: {e}")
# Fetch to view PDF on frontend
async def fetch_textbook_pdf(doc_id: str):
bucket = _get_textbook_fs()
return await bucket.open_download_stream_by_name(f"{doc_id}.pdf")
# Delete textbook when handshake failed
async def delete_textbook_pdf(doc_id: str):
bucket = _get_textbook_fs()
try:
file = await bucket.find({"filename": f"{doc_id}.pdf"}).to_list(1)
if file:
await bucket.delete(file[0]["_id"])
except Exception:
pass
|