Spaces:
Paused
Paused
Commit ·
eb2e1af
1
Parent(s): 7626f3a
Upd debug logs
Browse filesFiles changed (5)
17 unmodified lines18192021222317 unmodified linesfrom fastapi import FastAPI, WebSocketfrom app.routers import search, import_docapp = FastAPI()app.include_router(search.router, prefix="/search")17 unmodified lines18192021222324252627282930313233343517 unmodified linesfrom fastapi import FastAPI, WebSocketfrom app.routers import search, import_doc# Debuggerimport logginglogging.basicConfig(level=logging.DEBUG,format="%(asctime)s — %(name)s — %(levelname)s — %(message)s",force=True)logger = logging.getLogger("book-query")logger.setLevel(logging.DEBUG)logger.info("🚀 Starting Tutor Book Querier...")app = FastAPI()app.include_router(search.router, prefix="/search")
7 unmodified lines89101112134 unmodified lines1819202122232425262728293031323334353637383940414243444546474849505152535455565758596061627 unmodified linesimport asyncioimport httpxrouter = APIRouter()class ImportRequest(BaseModel):4 unmodified lines@router.post("")async def import_book(req: ImportRequest):source_lookup = {"google": google_books.fetch,"openlibrary": open_library.fetch,"ia": internet_archive.fetch}if req.source not in source_lookup:raise HTTPException(400, "Invalid source")result = await source_lookup[req.source](req.ref)print(f"[DEBUG] Import source result: {result}") # We need to debug out the result from Google API# Debugsif not result:print("[INFO] No download result returned from fetch().")raise HTTPException(403, "Download not permitted")if not result.get("download_url"):print(f"[INFO] No download URL. Viewability: {result.get('viewability', 'N/A')}")raise HTTPException(403, "Download not permitted")# Write temp file and save as Pdf from downloadable linkdownload_url = result["download_url"]file_path = f"/tmp/{req.candidate_id}.pdf"async with aiofiles.open(file_path, mode='wb') as f:async with httpx.AsyncClient() as client:r = await client.get(download_url)await f.write(r.content)with open(file_path, "rb") as f:await grid_fs_bucket.upload_from_stream(f"{req.candidate_id}.pdf", f)os.remove(file_path)doc = {"_id": req.candidate_id,"title": req.title,"status": "queued","metadata": result}asyncio.create_task(parse_and_index(req.candidate_id))return {"document_id": req.candidate_id, "status": "queued"}7 unmodified lines89101112131415164 unmodified lines21222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081827 unmodified linesimport asyncioimport httpximport logginglogger = logging.getLogger("book-query")router = APIRouter()class ImportRequest(BaseModel):4 unmodified lines@router.post("")async def import_book(req: ImportRequest):logger.info(f"📥 Received import request: {req.dict()}")source_lookup = {"google": google_books.fetch,"openlibrary": open_library.fetch,"ia": internet_archive.fetch}if req.source not in source_lookup:logger.warning(f"❌ Invalid source: {req.source}")raise HTTPException(400, "Invalid source")result = await source_lookup[req.source](req.ref)logger.debug(f"🔎 Fetch result for ref {req.ref}: {result}")# Debugsif not result:logger.warning(f"⛔️ No fetch result for {req.source} with ref {req.ref}")raise HTTPException(403, "Download not permitted")if not result.get("download_url"):logger.warning(f"📄 No download URL from {req.source}. Viewability: {result.get('viewability', 'unknown')}")raise HTTPException(403, "Download not permitted")# Write temp file and save as Pdf from downloadable linkdownload_url = result["download_url"]file_path = f"/tmp/{req.candidate_id}.pdf"logger.info(f"⬇️ Downloading from: {download_url}")# Read and write filetry:async with aiofiles.open(file_path, mode='wb') as f:async with httpx.AsyncClient() as client:r = await client.get(download_url)r.raise_for_status()await f.write(r.content)logger.info(f"✅ PDF saved to {file_path}")except Exception as e:logger.error(f"🚨 Failed to download or write PDF: {e}")raise HTTPException(500, "Failed to download PDF")# Save to buckettry:with open(file_path, "rb") as f:await grid_fs_bucket.upload_from_stream(f"{req.candidate_id}.pdf", f)os.remove(file_path)except Exception as e:logger.error(f"💥 Failed to upload to GridFS: {e}")raise HTTPException(500, "Storage failed")# Doc tagsdoc = {"_id": req.candidate_id,"title": req.title,"status": "queued","metadata": result}await db.documents.insert_one(doc)asyncio.create_task(parse_and_index(req.candidate_id))logger.info(f"📚 Document {req.candidate_id} queued for indexing")return {"document_id": req.candidate_id, "status": "queued"}
12345618 unmodified lines25262728# app/services/google_books.pyimport httpx, osfrom tenacity import retry, stop_after_attempt, wait_fixed@retry(stop=stop_after_attempt(3), wait=wait_fixed(1))async def search(q):18 unmodified lines]async def fetch(ref):return None # Google doesn't permit download1234567818 unmodified lines27282930313233# app/services/google_books.pyimport httpx, osfrom tenacity import retry, stop_after_attempt, wait_fixedimport logginglogger = logging.getLogger("book-query")@retry(stop=stop_after_attempt(3), wait=wait_fixed(1))async def search(q):18 unmodified lines]async def fetch(ref):logger = logging.getLogger("book-query")logger.debug(f"[Google] fetch() called with ref={ref}")return None # Always returns None, so import will 403
.DS_Store
app/.DS_Store
app/main.py+12
app/routers/import_doc.py+33-13
app/services/google_books.py+6-1