feat: lazy module loading and deferred pydantic build (#7316)
Co-authored-by: Michael Genson <genson.michael@gmail.com> Co-authored-by: Michael Genson <71845777+michael-genson@users.noreply.github.com>
This commit is contained in:
14 files changed
+86
-36
No files matched your search
@@ -1,4 +1 @@
|
||||
from .auth_provider import *
|
||||
from .credentials_provider import *
|
||||
from .ldap_provider import *
|
||||
from .openid_provider import *
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
from fastapi import APIRouter
|
||||
from recipe_scrapers import __version__ as recipe_scraper_version
|
||||
|
||||
from mealie.core.release_checker import get_latest_version
|
||||
from mealie.core.settings.static import APP_VERSION
|
||||
@@ -14,6 +13,7 @@ class AdminAboutController(BaseAdminController):
|
||||
@router.get("", response_model=AdminAboutInfo)
|
||||
def get_app_info(self):
|
||||
"""Get general application information"""
|
||||
from recipe_scrapers import __version__ as recipe_scraper_version
|
||||
|
||||
settings = self.settings
|
||||
|
||||
|
||||
@@ -11,7 +11,6 @@ from mealie.pkgs.stats.fs_stats import pretty_size
|
||||
from mealie.routes._base import BaseAdminController, controller
|
||||
from mealie.schema.admin.backup import AllBackups, BackupFile
|
||||
from mealie.schema.response.responses import ErrorResponse, FileTokenResponse, SuccessResponse
|
||||
from mealie.services.backups_v2.backup_v2 import BackupSchemaMismatch, BackupV2
|
||||
|
||||
logger = get_logger()
|
||||
router = APIRouter(prefix="/backups")
|
||||
@@ -43,6 +42,8 @@ class AdminBackupController(BaseAdminController):
|
||||
|
||||
@router.post("", status_code=status.HTTP_201_CREATED, response_model=SuccessResponse)
|
||||
def create_one(self):
|
||||
from mealie.services.backups_v2.backup_v2 import BackupV2
|
||||
|
||||
backup = BackupV2()
|
||||
|
||||
try:
|
||||
@@ -102,6 +103,8 @@ class AdminBackupController(BaseAdminController):
|
||||
|
||||
@router.post("/{file_name}/restore", response_model=SuccessResponse)
|
||||
def import_one(self, file_name: str):
|
||||
from mealie.services.backups_v2.backup_v2 import BackupSchemaMismatch, BackupV2
|
||||
|
||||
backup = BackupV2()
|
||||
|
||||
file = self._backup_path(file_name)
|
||||
|
||||
@@ -8,8 +8,6 @@ from pydantic import UUID4
|
||||
from mealie.core.dependencies.dependencies import get_temporary_path
|
||||
from mealie.routes._base import BaseAdminController, controller
|
||||
from mealie.schema.admin.debug import DebugResponse
|
||||
from mealie.schema.openai.general import OpenAIText
|
||||
from mealie.services.openai import OpenAILocalImage, OpenAIService
|
||||
|
||||
router = APIRouter(prefix="/debug")
|
||||
|
||||
@@ -22,6 +20,9 @@ class AdminDebugController(BaseAdminController):
|
||||
if not provider:
|
||||
return DebugResponse(success=False, response="Provider not found")
|
||||
|
||||
from mealie.schema.openai.general import OpenAIText
|
||||
from mealie.services.openai import OpenAILocalImage, OpenAIService
|
||||
|
||||
with get_temporary_path() as temp_path:
|
||||
if image:
|
||||
if not image.filename:
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
from typing import Annotated, Any
|
||||
|
||||
from authlib.integrations.starlette_client import OAuth, OAuthError
|
||||
from fastapi import APIRouter, Depends, Header, Request, Response, status
|
||||
from fastapi.exceptions import HTTPException
|
||||
from fastapi.responses import RedirectResponse
|
||||
@@ -12,7 +11,6 @@ from mealie.core import root_logger, security
|
||||
from mealie.core.config import get_app_settings
|
||||
from mealie.core.dependencies import get_current_user
|
||||
from mealie.core.exceptions import MissingClaimException, UserLockedOut
|
||||
from mealie.core.security.providers.openid_provider import OpenIDProvider
|
||||
from mealie.core.security.security import get_auth_provider
|
||||
from mealie.db.db_setup import generate_session
|
||||
from mealie.lang import get_locale_provider
|
||||
@@ -28,7 +26,10 @@ logger = root_logger.get_logger("auth")
|
||||
|
||||
|
||||
settings = get_app_settings()
|
||||
oauth = None
|
||||
if settings.OIDC_READY:
|
||||
from authlib.integrations.starlette_client import OAuth
|
||||
|
||||
oauth = OAuth(cache=AuthCache())
|
||||
scope = None
|
||||
if settings.OIDC_SCOPES_OVERRIDE:
|
||||
@@ -123,6 +124,8 @@ async def oauth_callback(request: Request, session: Session = Depends(generate_s
|
||||
|
||||
token = await client.authorize_access_token(request)
|
||||
|
||||
from mealie.core.security.providers.openid_provider import OpenIDProvider
|
||||
|
||||
auth = None
|
||||
try:
|
||||
auth_provider = OpenIDProvider(session, token["userinfo"])
|
||||
@@ -147,7 +150,7 @@ async def oauth_callback(request: Request, session: Session = Depends(generate_s
|
||||
@public_router.get("/oauth/native/config", response_model=OIDCNativeConfig)
|
||||
async def oauth_native_config():
|
||||
"""Return the parameters a native client needs to build its own OIDC authorization request."""
|
||||
if not settings.OIDC_READY:
|
||||
if not settings.OIDC_READY or not oauth:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="OIDC is not configured",
|
||||
@@ -170,12 +173,14 @@ async def oauth_native_token(data: NativeOIDCTokenRequest, session: Session = De
|
||||
session cookie. This lets passkey-capable system-browser logins (e.g. Pocket ID) work, which
|
||||
the cookie-coupled web callback cannot support.
|
||||
"""
|
||||
if not settings.OIDC_READY:
|
||||
if not settings.OIDC_READY or not oauth:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="OIDC is not configured",
|
||||
)
|
||||
|
||||
from authlib.integrations.starlette_client import OAuthError
|
||||
|
||||
client = oauth.create_client("oidc")
|
||||
try:
|
||||
token = await client.fetch_access_token(
|
||||
@@ -188,6 +193,8 @@ async def oauth_native_token(data: NativeOIDCTokenRequest, session: Session = De
|
||||
logger.error("[OIDC] Native token exchange failed: %s", e)
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED) from e
|
||||
|
||||
from mealie.core.security.providers.openid_provider import OpenIDProvider
|
||||
|
||||
auth = None
|
||||
try:
|
||||
auth_provider = OpenIDProvider(session, userinfo)
|
||||
|
||||
@@ -4,7 +4,6 @@ import pathlib
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
from bs4 import BeautifulSoup
|
||||
from fastapi import Depends, FastAPI, Response
|
||||
from fastapi.encoders import jsonable_encoder
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
@@ -68,6 +67,8 @@ def escape(content: Any) -> Any:
|
||||
|
||||
|
||||
def inject_meta(contents: str, tags: list[MetaTag]) -> str:
|
||||
from bs4 import BeautifulSoup
|
||||
|
||||
soup = BeautifulSoup(contents, "lxml")
|
||||
scraped_meta_tags = soup.find_all("meta")
|
||||
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
from typing import Protocol
|
||||
|
||||
import apprise
|
||||
import requests
|
||||
from fastapi.encoders import jsonable_encoder
|
||||
|
||||
from mealie.services.event_bus_service.event_types import Event
|
||||
@@ -13,6 +11,8 @@ class PublisherLike(Protocol):
|
||||
|
||||
class ApprisePublisher:
|
||||
def __init__(self, hard_fail=False) -> None:
|
||||
import apprise
|
||||
|
||||
asset = apprise.AppriseAsset(
|
||||
async_mode=True,
|
||||
image_url_mask="https://raw.githubusercontent.com/mealie-recipes/mealie/9571816ac4eed5beacfc0abf6c03eff1427fd0eb/frontend/static/icons/android-chrome-maskable-512x512.png",
|
||||
@@ -42,6 +42,8 @@ class WebhookPublisher:
|
||||
self.hard_fail = hard_fail
|
||||
|
||||
def publish(self, event: Event, notification_urls: list[str]):
|
||||
import requests
|
||||
|
||||
event_payload = jsonable_encoder(event)
|
||||
for url in notification_urls:
|
||||
r = requests.post(url, json=event_payload, timeout=15)
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import inspect
|
||||
import json
|
||||
@@ -5,11 +7,12 @@ import os
|
||||
from abc import ABC, abstractmethod
|
||||
from pathlib import Path
|
||||
from textwrap import dedent
|
||||
from typing import TypeVar
|
||||
from typing import TYPE_CHECKING, TypeVar
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from openai import AsyncOpenAI
|
||||
from openai.types.chat import ChatCompletion
|
||||
|
||||
import openai
|
||||
from openai import AsyncOpenAI
|
||||
from openai.types.chat import ChatCompletion
|
||||
from pydantic import BaseModel, field_validator
|
||||
|
||||
from mealie.core import exceptions, root_logger
|
||||
@@ -136,6 +139,8 @@ class OpenAIService(BaseService):
|
||||
super().__init__()
|
||||
|
||||
def get_client(self, provider: AIProviderOut) -> AsyncOpenAI:
|
||||
from openai import AsyncOpenAI
|
||||
|
||||
return AsyncOpenAI(
|
||||
base_url=provider.base_url or None,
|
||||
api_key=provider.api_key,
|
||||
@@ -290,6 +295,7 @@ class OpenAIService(BaseService):
|
||||
provider: AIProviderOut | None = None,
|
||||
) -> T | None:
|
||||
"""Send data to OpenAI and return the response message content"""
|
||||
import openai
|
||||
|
||||
try:
|
||||
provider = provider or self._get_provider(attachments)
|
||||
@@ -309,6 +315,8 @@ class OpenAIService(BaseService):
|
||||
raise Exception(f"OpenAI Request Failed. {e.__class__.__name__}: {e}") from e
|
||||
|
||||
async def transcribe_audio(self, audio_file_path: Path) -> str | None:
|
||||
import openai
|
||||
|
||||
if not self.audio_provider:
|
||||
raise OpenAINotEnabledException("No audio provider set")
|
||||
|
||||
|
||||
@@ -4,9 +4,6 @@ from collections.abc import Awaitable, Callable
|
||||
from pathlib import Path
|
||||
from typing import TypedDict
|
||||
|
||||
import yt_dlp
|
||||
from yt_dlp.extractor.generic import GenericIE
|
||||
|
||||
from mealie.core import exceptions
|
||||
from mealie.core.root_logger import get_logger
|
||||
|
||||
@@ -29,6 +26,9 @@ class TranscribedAudio(TypedDict):
|
||||
@functools.cache
|
||||
def get_yt_dlp_extractors() -> list:
|
||||
"""Build and cache the yt-dlp extractor list once per process lifetime."""
|
||||
import yt_dlp
|
||||
from yt_dlp.extractor.generic import GenericIE
|
||||
|
||||
return [ie for ie in yt_dlp.extractor.gen_extractors() if ie.working() and not isinstance(ie, GenericIE)]
|
||||
|
||||
|
||||
@@ -57,6 +57,8 @@ def parse_subtitle_content(subtitle_content: str) -> str:
|
||||
def download_video(url: str, temp_path: Path) -> TranscribedAudio:
|
||||
"""Downloads audio and subtitles from a video URL."""
|
||||
|
||||
import yt_dlp
|
||||
|
||||
output_template = temp_path / "mealie" # No extension here
|
||||
|
||||
ydl_opts = {
|
||||
|
||||
@@ -1,13 +1,17 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from fractions import Fraction
|
||||
from itertools import zip_longest
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from ingredient_parser import parse_ingredient
|
||||
from ingredient_parser.dataclasses import CompositeIngredientAmount, IngredientAmount
|
||||
from ingredient_parser.dataclasses import ParsedIngredient as IngredientParserParsedIngredient
|
||||
from pydantic import UUID4
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ingredient_parser.dataclasses import IngredientAmount
|
||||
from ingredient_parser.dataclasses import ParsedIngredient as IngredientParserParsedIngredient
|
||||
|
||||
from mealie.core.root_logger import get_logger
|
||||
from mealie.lang.providers import Translator
|
||||
from mealie.schema.recipe import RecipeIngredient
|
||||
@@ -21,7 +25,7 @@ from mealie.schema.recipe.recipe_ingredient import (
|
||||
RegisteredParser,
|
||||
)
|
||||
|
||||
from . import brute, openai
|
||||
from . import brute
|
||||
from ._base import ABCIngredientParser
|
||||
from .parser_utils import extract_quantity_from_string
|
||||
|
||||
@@ -96,6 +100,8 @@ class NLPParser(ABCIngredientParser):
|
||||
|
||||
@classmethod
|
||||
def _extract_amount(cls, ingredient: IngredientParserParsedIngredient) -> IngredientAmount:
|
||||
from ingredient_parser.dataclasses import CompositeIngredientAmount, IngredientAmount
|
||||
|
||||
if not (ingredient_amounts := ingredient.amount):
|
||||
return IngredientAmount(
|
||||
quantity=Fraction(0), quantity_max=Fraction(0), unit="", text="", confidence=0, starting_index=-1
|
||||
@@ -162,6 +168,8 @@ class NLPParser(ABCIngredientParser):
|
||||
return note, confidence
|
||||
|
||||
def _convert_ingredient(self, ingredient: IngredientParserParsedIngredient) -> ParsedIngredient:
|
||||
from ingredient_parser.dataclasses import CompositeIngredientAmount
|
||||
|
||||
ing_parts: list[_IngredientPart] = []
|
||||
|
||||
for amount, ing_name in zip_longest(ingredient.amount, ingredient.name, fillvalue=None):
|
||||
@@ -252,6 +260,8 @@ class NLPParser(ABCIngredientParser):
|
||||
return self.find_ingredient_match(parsed_ingredient)
|
||||
|
||||
async def parse_one(self, ingredient_string: str) -> ParsedIngredient:
|
||||
from ingredient_parser import parse_ingredient
|
||||
|
||||
database_units = {}
|
||||
for ingredient_unit in self.data_matcher.units_by_id.values():
|
||||
if ingredient_unit.name:
|
||||
@@ -272,7 +282,6 @@ class NLPParser(ABCIngredientParser):
|
||||
__registrar: dict[RegisteredParser, type[ABCIngredientParser]] = {
|
||||
RegisteredParser.nlp: NLPParser,
|
||||
RegisteredParser.brute: BruteForceParser,
|
||||
RegisteredParser.openai: openai.OpenAIParser,
|
||||
}
|
||||
|
||||
|
||||
@@ -280,7 +289,11 @@ def get_parser(
|
||||
parser: RegisteredParser, group_id: UUID4, session: Session, translator: Translator
|
||||
) -> ABCIngredientParser:
|
||||
"""
|
||||
get_parser returns an ingrdeint parser based on the string enum value
|
||||
get_parser returns an ingredient parser based on the string enum value
|
||||
passed in.
|
||||
"""
|
||||
if parser == RegisteredParser.openai:
|
||||
from .openai import OpenAIParser
|
||||
|
||||
return OpenAIParser(group_id, session, translator)
|
||||
return __registrar.get(parser, NLPParser)(group_id, session, translator)
|
||||
@@ -1,8 +1,10 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING, Literal, overload
|
||||
|
||||
from pint import Quantity, Unit, UnitRegistry
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pint import Quantity, Unit
|
||||
|
||||
from mealie.schema.recipe.recipe_ingredient import CreateIngredientUnit
|
||||
|
||||
|
||||
@@ -19,6 +21,8 @@ class UnitNotFound(Exception):
|
||||
|
||||
class UnitConverter:
|
||||
def __init__(self):
|
||||
from pint import UnitRegistry
|
||||
|
||||
self.ureg = UnitRegistry()
|
||||
|
||||
def _resolve_ounce(self, unit_1: Unit, unit_2: Unit) -> tuple[Unit, Unit]:
|
||||
@@ -53,6 +57,8 @@ class UnitConverter:
|
||||
If strict is True, raises UnitNotFound instead of returning a string.
|
||||
If the input is already a parsed pint.Unit, returns it as-is.
|
||||
"""
|
||||
from pint import Unit
|
||||
|
||||
if isinstance(unit, Unit):
|
||||
return unit
|
||||
|
||||
@@ -65,6 +71,7 @@ class UnitConverter:
|
||||
|
||||
def can_convert(self, unit: str | Unit, to_unit: str | Unit) -> bool:
|
||||
"""Whether or not a given unit can be converted into another unit."""
|
||||
from pint import Unit
|
||||
|
||||
unit = self.parse(unit)
|
||||
to_unit = self.parse(to_unit)
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import shutil
|
||||
from datetime import UTC, datetime
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from abc import ABC, abstractmethod
|
||||
from collections.abc import Awaitable, Callable
|
||||
from typing import Any
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
import extruct
|
||||
from fastapi import HTTPException, status
|
||||
from recipe_scrapers import NoSchemaFoundInWildMode, SchemaScraperFactory, scrape_html
|
||||
from slugify import slugify
|
||||
from w3lib.html import get_base_url
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from recipe_scrapers import SchemaScraperFactory
|
||||
|
||||
from mealie.core import exceptions
|
||||
from mealie.core.dependencies.dependencies import get_temporary_path
|
||||
@@ -208,6 +209,8 @@ class RecipeScraperPackage(ABCScraperStrategy):
|
||||
return recipe, extras
|
||||
|
||||
async def scrape_url(self) -> SchemaScraperFactory.SchemaScraper | Any | None:
|
||||
from recipe_scrapers import NoSchemaFoundInWildMode, scrape_html
|
||||
|
||||
recipe_html = await self.get_html(self.url)
|
||||
|
||||
try:
|
||||
@@ -403,6 +406,10 @@ class RecipeScraperOpenGraph(ABCScraperStrategy):
|
||||
def og_fields(properties: list[tuple[str, str]], field_name: str) -> list[str]:
|
||||
return list({val for name, val in properties if name == field_name})
|
||||
|
||||
import extruct
|
||||
from slugify import slugify
|
||||
from w3lib.html import get_base_url
|
||||
|
||||
base_url = get_base_url(html, self.url)
|
||||
data = extruct.extract(html, base_url=base_url, errors="log")
|
||||
try:
|
||||
|
||||
@@ -101,7 +101,7 @@ def test_post_test_webhook(
|
||||
mock_calls.append((args, kwargs))
|
||||
return MockResponse()
|
||||
|
||||
monkeypatch.setattr("mealie.services.event_bus_service.publisher.requests.post", mock_post)
|
||||
monkeypatch.setattr("requests.post", mock_post)
|
||||
|
||||
# Create a webhook and post it
|
||||
response = api_client.post(
|
||||
|
||||
Reference in new issue
Block a user