station-announcer/station_announcer/__init__.py

79 lines
2.4 KiB
Python

"""Package initialization for the alt text generator app."""
import sys
from pathlib import Path
from flask import Flask
sys.path.append("/home/edward/src/2024/UniAuth") # isort:skip
from .cache import AltTextCache
from .config import DEFAULT_OPENAI_MODEL, load_settings
from .immich import ImmichClient
from .mastodon import MastodonClient
from .openai_client import AltTextGenerator
def _load_hashtag_counts(path: Path) -> str | None:
"""Return newline-delimited hashtag counts formatted for prompts."""
try:
return path.read_text()
except FileNotFoundError:
return None
def create_app() -> Flask:
"""Create and configure the Flask application."""
package_path = Path(__file__).resolve().parent
project_root = package_path.parent
app = Flask(
__name__,
template_folder=str(project_root / "templates"),
static_folder=str(project_root / "static"),
)
settings = load_settings()
app.config.update(settings)
hashtag_counts = _load_hashtag_counts(project_root / "hash_tag_counts")
if hashtag_counts:
app.config["HASHTAG_COUNTS_TEXT"] = hashtag_counts
secret_key = app.config.get("SECRET_KEY") or "dev-secret-key"
app.config["SECRET_KEY"] = secret_key
app.config["UNIAUTH_URL"] = "https://edwardbetts.com/UniAuth"
app.config["REQUIRE_AUTH"] = True
app.config["AUTH_CALLBACK_ENDPOINT"] = "main.auth_callback"
instance_dir = Path(app.instance_path)
instance_dir.mkdir(parents=True, exist_ok=True)
db_path = app.config.get("STATION_DB")
if not db_path:
db_path = str(instance_dir / "station_announcer.db")
app.config["STATION_DB"] = db_path
app.immich_client = ImmichClient(
base_url=app.config["IMMICH_API_URL"],
api_key=app.config["IMMICH_API_KEY"],
)
app.alt_text_cache = AltTextCache(db_path)
app.alt_text_generator = AltTextGenerator(
api_key=app.config["OPENAI_API_KEY"],
model=app.config.get("OPENAI_MODEL", DEFAULT_OPENAI_MODEL),
)
mastodon_token = app.config.get("MASTODON_ACCESS_TOKEN")
if mastodon_token:
app.mastodon_client = MastodonClient(
base_url=app.config.get("MASTODON_BASE_URL", "http://localhost:3000"),
access_token=mastodon_token,
)
else:
app.mastodon_client = None
from . import routes # pragma: no cover
app.register_blueprint(routes.bp)
return app