84 lines
2.6 KiB
Python
84 lines
2.6 KiB
Python
"""Trail guide API: scrape, PDF extraction (drafts), review/save, CRUD."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from pathlib import Path
|
|
|
|
from fastapi import APIRouter, HTTPException, UploadFile
|
|
from pydantic import BaseModel
|
|
from pypdf import PdfReader
|
|
|
|
from app.config import settings
|
|
from app.deps import get_llm, get_store
|
|
from app.models.trail_guide import TrailGuide
|
|
from app.services.scraper import guide_from_extraction, scrape_trail_guide
|
|
|
|
router = APIRouter(prefix="/api/trails", tags=["trails"])
|
|
|
|
|
|
class ScrapeBody(BaseModel):
|
|
url: str
|
|
|
|
|
|
@router.post("/scrape")
|
|
def scrape(body: ScrapeBody) -> TrailGuide:
|
|
"""Returns a DRAFT guide for review; client saves it via POST /api/trails."""
|
|
try:
|
|
return scrape_trail_guide(body.url, get_llm())
|
|
except Exception as e:
|
|
raise HTTPException(502, f"scrape failed: {e}")
|
|
|
|
|
|
@router.post("/upload-pdf")
|
|
async def upload_pdf(file: UploadFile) -> TrailGuide:
|
|
"""PDF -> pypdf text -> LLM extraction -> DRAFT guide for review."""
|
|
if not (file.filename or "").lower().endswith(".pdf"):
|
|
raise HTTPException(400, "expected a .pdf file")
|
|
raw = await file.read()
|
|
pdf_dir = Path(settings.pdf_dir)
|
|
pdf_dir.mkdir(parents=True, exist_ok=True)
|
|
pdf_path = pdf_dir / Path(file.filename).name
|
|
pdf_path.write_bytes(raw)
|
|
try:
|
|
reader = PdfReader(str(pdf_path))
|
|
text = "\n".join((page.extract_text() or "") for page in reader.pages)
|
|
except Exception as e:
|
|
raise HTTPException(400, f"could not read PDF: {e}")
|
|
llm = get_llm()
|
|
extracted: dict = {}
|
|
if llm.configured and text.strip():
|
|
try:
|
|
extracted = llm.extract_trail_data(text)
|
|
except Exception:
|
|
pass # user reviews from raw text instead
|
|
return guide_from_extraction(
|
|
extracted, source="pdf", pdf_path=str(pdf_path),
|
|
raw_text=text[:50000], fallback_name=Path(file.filename).stem,
|
|
)
|
|
|
|
|
|
@router.post("")
|
|
def save_guide(guide: TrailGuide) -> TrailGuide:
|
|
"""Save a reviewed/edited guide (the manual-review confirmation step)."""
|
|
return get_store().save_trail_guide(guide)
|
|
|
|
|
|
@router.get("")
|
|
def list_guides():
|
|
return get_store().list_trail_guides()
|
|
|
|
|
|
@router.get("/{guide_id}")
|
|
def get_guide(guide_id: str) -> TrailGuide:
|
|
guide = get_store().get_trail_guide(guide_id)
|
|
if guide is None:
|
|
raise HTTPException(404, "trail guide not found")
|
|
return guide
|
|
|
|
|
|
@router.delete("/{guide_id}")
|
|
def delete_guide(guide_id: str):
|
|
if not get_store().delete_trail_guide(guide_id):
|
|
raise HTTPException(404, "trail guide not found")
|
|
return {"deleted": guide_id}
|