Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,9 @@ user row. The changes that makes possible are specified in
- **Import from a link** — paste a YouTube (or Rumble, Odysee, Vimeo…) URL and it arrives
titled, attributed, tagged and split into its chapters, with the site's captions as a
transcript when there is no Deepgram key. Playlists too. See
[`docs/url-import.md`](docs/url-import.md).
[`docs/url-import.md`](docs/url-import.md). A single picture can be imported by its
address too, which is how Video Creator files the pictures its image search finds
([`docs/image-import.md`](docs/image-import.md)).
- **Find the moment** — full-text search over names, descriptions, summaries, tags and
transcripts, fused with semantic search so half-remembered wording still lands. Hits
in audio and video come back with a timestamp you can jump straight to.
Expand Down
6 changes: 3 additions & 3 deletions backend/app/enrichment/page_import.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ def similar_in_library(session: Session, user_id: str, tracks: list[PageTrack])
return found


def _same_file(session: Session, user_id: str, path: Path) -> Optional[Asset]:
def same_file(session: Session, user_id: str, path: Path) -> Optional[Asset]:
"""An asset in this library with exactly these bytes, if there is one.

The checksum every stored file already carries is what catches a duplicate the URL
Expand Down Expand Up @@ -334,7 +334,7 @@ def report(received: int, total: Optional[int]) -> None:
raise PageImportError(str(exc)) from exc

progress("Checking for a copy already here", 86, "")
duplicate = _same_file(session, job.user_id, path)
duplicate = same_file(session, job.user_id, path)
if duplicate is not None:
# The download is thrown away with the temp directory. What the page said
# still fills the copy's blanks, so a track uploaded bare gains its credits
Expand Down Expand Up @@ -490,7 +490,7 @@ def import_saved(
continue

track = matches.get(name)
duplicate = _same_file(session, user_id, path)
duplicate = same_file(session, user_id, path)
if duplicate is not None:
if track is not None:
apply_track_metadata(session, duplicate, track, fill_blanks_only=True)
Expand Down
98 changes: 81 additions & 17 deletions backend/app/ingest/web.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Fetching a web page, or one audio file named on it, on the user's behalf.
"""Fetching a web page, or one audio file or picture named on it, on the user's behalf.

For importing tracks from a page (`ingest/page_tracks.py`). The same rules as
For importing tracks from a page (`ingest/page_tracks.py`) and pictures found by an
image search (`services/image_import.py`). The same rules as
`generation/download.py`, which is fal-specific (its errors, its retry policy, image and
video only), restated here for a page and a track rather than shared through a flag:

Expand Down Expand Up @@ -41,6 +42,8 @@
# A long, high-bitrate track. Anything bigger is not a soundtrack.
MAX_TRACK_BYTES = 200 * 1024 * 1024
MAX_TRACK_SECONDS = 15 * 60
# A large photograph. A picture for a video frame needs no more than a few megapixels.
MAX_IMAGE_BYTES = 40 * 1024 * 1024

# Says what is asking, so a site that wants to can tell this apart from a browser and
# from a crawler. It is one person's library fetching the tracks they picked.
Expand All @@ -67,6 +70,24 @@
}


_IMAGE_TYPES = {
"image/jpeg": ".jpg",
"image/jpg": ".jpg",
"image/pjpeg": ".jpg",
"image/png": ".png",
"image/gif": ".gif",
"image/webp": ".webp",
"image/avif": ".avif",
"image/bmp": ".bmp",
"image/tiff": ".tiff",
}
# What a picture from the web may be stored as. Narrower than an upload's list: no SVG,
# which is a document that can carry script and is served back from this origin, and
# none of the camera formats (HEIC) or icons a person might upload but a site sends a
# browser as something else anyway.
WEB_IMAGE_EXTENSIONS = frozenset(_IMAGE_TYPES.values()) | {".jpeg", ".tif"}


class WebFetchError(Exception):
"""A page or a track could not be fetched. The message is worded for the user."""

Expand Down Expand Up @@ -161,30 +182,57 @@ def download_audio(
with an HTML page (a login wall, a "download starting" interstitial) must not land in
the library as a broken track.
"""
return _download(url, workdir, stem, what="track", extension=_audio_extension,
refused="That link is not an audio file", max_bytes=max_bytes,
on_progress=on_progress)


def download_image(url: str, workdir: Path, stem: str, *, max_bytes: int = MAX_IMAGE_BYTES) -> Path:
"""Fetch one picture into `workdir/<stem><ext>` and return the path.

The same refusal as a track's: a URL that answers with a page is not a picture. An
image search's "image URL" is often a page that shows one, or a hotlink guard's
placeholder, and that must not become an asset.
"""
return _download(url, workdir, stem, what="picture", extension=_image_extension,
refused="That link is not a picture GAM can store", max_bytes=max_bytes)


def _download(
url: str,
workdir: Path,
stem: str,
*,
what: str,
extension: Callable[[str, Optional[str]], Optional[str]],
refused: str,
max_bytes: int,
on_progress: Optional[Progress] = None,
) -> Path:
report = on_progress or (lambda _received, _total: None)
try:
with _client("identity") as client, _get(client, url) as (final, response):
if response.status_code >= 400:
raise _status_error("track", response)
raise _status_error(what, response)
encoding = response.headers.get("content-encoding", "").strip().lower()
if encoding not in ("", "identity"):
raise WebFetchError("The site sent the track compressed, which is refused")
raise WebFetchError(f"The site sent the {what} compressed, which is refused")

extension = _audio_extension(final, response.headers.get("content-type"))
if extension is None:
raise WebFetchError("That link is not an audio file")
suffix = extension(final, response.headers.get("content-type"))
if suffix is None:
raise WebFetchError(refused)

total = _content_length(response)
if total is not None and total > max_bytes:
raise _too_large(max_bytes)
raise _too_large(what, max_bytes)

destination = workdir / f"{stem}{extension}"
_stream_to(response, destination, max_bytes=max_bytes, total=total, report=report)
destination = workdir / f"{stem}{suffix}"
_stream_to(response, destination, what=what, max_bytes=max_bytes, total=total, report=report)
return destination
except httpx.TimeoutException as exc:
raise WebFetchError("The track did not download in time") from exc
raise WebFetchError(f"The {what} did not download in time") from exc
except httpx.RequestError as exc:
raise WebFetchError(f"Could not download the track ({type(exc).__name__})") from exc
raise WebFetchError(f"Could not download the {what} ({type(exc).__name__})") from exc


def _audio_extension(url: str, content_type: Optional[str]) -> Optional[str]:
Expand All @@ -195,8 +243,24 @@ def _audio_extension(url: str, content_type: Optional[str]) -> Optional[str]:
return _AUDIO_TYPES.get(media_type)


def _image_extension(url: str, content_type: Optional[str]) -> Optional[str]:
# The server's type first, unlike a track: picture URLs are full of `.php?id=` and of
# CDNs that send WebP from a `.jpg` path to browsers that accept it, and the file must
# be stored under what it is. The path is the fallback for servers that send
# `application/octet-stream`.
media_type = (content_type or "").split(";", 1)[0].strip().lower()
if media_type in _IMAGE_TYPES:
return _IMAGE_TYPES[media_type]
if media_type.startswith("image/") or media_type in ("", "application/octet-stream", "binary/octet-stream"):
from_path = extension_of(urlsplit(url).path)
if from_path in WEB_IMAGE_EXTENSIONS:
return from_path
return None


def _stream_to(
response: httpx.Response, destination: Path, *, max_bytes: int, total: Optional[int], report: Progress
response: httpx.Response, destination: Path, *, what: str, max_bytes: int, total: Optional[int],
report: Progress,
) -> None:
received = 0
started = monotonic()
Expand All @@ -205,9 +269,9 @@ def _stream_to(
for chunk in response.iter_bytes():
received += len(chunk)
if received > max_bytes:
raise _too_large(max_bytes)
raise _too_large(what, max_bytes)
if monotonic() - started > MAX_TRACK_SECONDS:
raise WebFetchError("The track did not download in time")
raise WebFetchError(f"The {what} did not download in time")
handle.write(chunk)
report(received, total)
except BaseException:
Expand All @@ -216,5 +280,5 @@ def _stream_to(
raise


def _too_large(max_bytes: int) -> WebFetchError:
return WebFetchError(f"The track is larger than the {max_bytes // (1024 * 1024)} MB limit")
def _too_large(what: str, max_bytes: int) -> WebFetchError:
return WebFetchError(f"The {what} is larger than the {max_bytes // (1024 * 1024)} MB limit")
62 changes: 60 additions & 2 deletions backend/app/routers/imports.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

from typing import List, Optional

from fastapi import APIRouter, Depends, File, HTTPException, UploadFile, status
from fastapi import APIRouter, Depends, File, HTTPException, Response, UploadFile, status
from pydantic import BaseModel, Field
from sqlmodel import Session

Expand All @@ -26,8 +26,12 @@
from app.models.job import KIND_IMPORT_TRACK, KIND_IMPORT_URL
from app.schemas import DataResponse
from app.safe_url import require_safe_external_url
from app.schemas_assets import AssetRead
from app.schemas_jobs import ActivityJobRead
from app.storage import capacity
from app.services import assets as asset_service
from app.services import image_import
from app.services import tags as tag_service
from app.storage import build_storage, capacity

router = APIRouter()

Expand Down Expand Up @@ -78,6 +82,60 @@ def start_url_import(
return DataResponse(data=KINDS["enrichment"].to_activity(job))


# ─── one picture, by its address ─────────────────────────────────────────────


class ImageImportCreate(BaseModel):
"""A picture an image search found, as the person chose it."""

image_url: str = Field(min_length=1, max_length=MAX_URL)
page_url: Optional[str] = Field(default=None, max_length=MAX_URL)
title: Optional[str] = Field(default=None, max_length=500)
description: Optional[str] = Field(default=None, max_length=20_000)
tags: List[str] = Field(default_factory=list, max_length=20)


@router.post("/import-image", response_model=DataResponse[AssetRead], status_code=status.HTTP_201_CREATED)
def import_image(
payload: ImageImportCreate,
response: Response,
user: CurrentUser,
session: Session = Depends(get_session),
) -> DataResponse[AssetRead]:
"""Download one picture and catalogue it. 201 with the new asset, or 200 with the
one already here (the same address, or the same bytes).

Inline rather than queued: see `services/image_import.py`. The address is checked
against private address space on every redirect hop, by `ingest/web.py`.
"""
capacity.require_room()
request = image_import.ImageImport(
image_url=payload.image_url.strip(),
page_url=(payload.page_url or "").strip() or None,
title=payload.title,
description=payload.description,
tags=[t for t in payload.tags if t.strip()],
)
try:
result = image_import.import_image(session, user.id, request)
except image_import.ImageImportError as exc:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail={"code": "image_unavailable", "message": str(exc)},
)
except web.WebFetchError as exc: # the address check, before anything is fetched
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail={"code": "unsafe_url", "message": str(exc)},
)
if result.existing:
response.status_code = status.HTTP_200_OK
asset = result.asset
return DataResponse(
data=asset_service.to_read_model(asset, build_storage(), tag_service.tags_for(session, asset.id))
)


# ─── tracks from a music library's page ──────────────────────────────────────


Expand Down
Loading
Loading