Spaces:
Running on Zero
Running on Zero
add modal shortener support for iOS
Browse files- README.md +1 -0
- app.py +21 -6
- modal_requirements.txt +34 -0
- modal_service.py +187 -0
- qr_modal_contract.py +225 -0
- qr_modal_loader.py +16 -0
- qr_modal_requirements.py +14 -0
- runtime_config.py +7 -0
- tests-unit/modal_service_test/test_qr_modal_contract.py +57 -0
- tests-unit/utils/runtime_config_test.py +21 -0
README.md
CHANGED
|
@@ -50,6 +50,7 @@ When enabled in the UI, URL mode can replace the QR payload with a `qrcut.co` sh
|
|
| 50 |
- `POSTHOG_HOST` (optional, defaults to `https://us.i.posthog.com`)
|
| 51 |
- `ANALYTICS_ENABLED` (optional, defaults to `true`)
|
| 52 |
- `ANALYTICS_DEFAULT_OPT_IN` (optional, defaults to `false`)
|
|
|
|
| 53 |
- `URL_SHORTENER_API_URL` (optional, for example `https://qrcut.co/shorten`)
|
| 54 |
- `URL_SHORTENER_API_KEY` (optional, private API key for the HF Space)
|
| 55 |
- `URL_SHORTENER_SOURCE_APP` (optional, defaults to `ai_qr_generator`)
|
|
|
|
| 50 |
- `POSTHOG_HOST` (optional, defaults to `https://us.i.posthog.com`)
|
| 51 |
- `ANALYTICS_ENABLED` (optional, defaults to `true`)
|
| 52 |
- `ANALYTICS_DEFAULT_OPT_IN` (optional, defaults to `false`)
|
| 53 |
+
- `ANALYTICS_PRODUCT` (optional, defaults to `ai_qr_generator`; set Modal/iOS deployments to `arti_qrcode_app` when sharing the same analytics tables)
|
| 54 |
- `URL_SHORTENER_API_URL` (optional, for example `https://qrcut.co/shorten`)
|
| 55 |
- `URL_SHORTENER_API_KEY` (optional, private API key for the HF Space)
|
| 56 |
- `URL_SHORTENER_SOURCE_APP` (optional, defaults to `ai_qr_generator`)
|
app.py
CHANGED
|
@@ -29,6 +29,7 @@ import torch
|
|
| 29 |
from huggingface_hub import hf_hub_download
|
| 30 |
from PIL import Image
|
| 31 |
import kornia.color # For RGB→HSV conversion in Stable Cascade filter
|
|
|
|
| 32 |
|
| 33 |
# ── Export helpers (PNG + embedded SVG download) ──────────────────────────────
|
| 34 |
import base64
|
|
@@ -66,6 +67,7 @@ POSTHOG_HOST = os.getenv("POSTHOG_HOST", "https://us.i.posthog.com").rstrip("/")
|
|
| 66 |
POSTHOG_API_KEY = os.getenv("POSTHOG_API_KEY", "") or os.getenv(
|
| 67 |
"POSTHOG_SECRET_KEY", ""
|
| 68 |
)
|
|
|
|
| 69 |
URL_SHORTENER_API_URL = os.getenv("URL_SHORTENER_API_URL", "").rstrip("/")
|
| 70 |
URL_SHORTENER_API_KEY = os.getenv("URL_SHORTENER_API_KEY", "")
|
| 71 |
URL_SHORTENER_SOURCE_APP = os.getenv("URL_SHORTENER_SOURCE_APP", "ai_qr_generator")
|
|
@@ -343,6 +345,9 @@ def _maybe_shorten_url_for_qr(
|
|
| 343 |
if input_type != "URL" or not _normalize_bool(use_temporary_short_link):
|
| 344 |
return result
|
| 345 |
if not URL_SHORTENER_API_URL or not URL_SHORTENER_API_KEY:
|
|
|
|
|
|
|
|
|
|
| 346 |
return {
|
| 347 |
**result,
|
| 348 |
"error": "shortener is not configured on the server",
|
|
@@ -355,6 +360,9 @@ def _maybe_shorten_url_for_qr(
|
|
| 355 |
"X-Source-App": URL_SHORTENER_SOURCE_APP,
|
| 356 |
}
|
| 357 |
try:
|
|
|
|
|
|
|
|
|
|
| 358 |
request_obj = urllib_request.Request(
|
| 359 |
URL_SHORTENER_API_URL,
|
| 360 |
data=request_body,
|
|
@@ -368,6 +376,12 @@ def _maybe_shorten_url_for_qr(
|
|
| 368 |
short_url = str(payload.get("short_url") or "").strip()
|
| 369 |
if not short_url:
|
| 370 |
raise ValueError("shortener returned an empty short URL")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 371 |
return {
|
| 372 |
"applied": True,
|
| 373 |
"effective_qr_text": _normalize_qr_text_for_validation(short_url, "URL"),
|
|
@@ -383,6 +397,7 @@ def _maybe_shorten_url_for_qr(
|
|
| 383 |
ValueError,
|
| 384 |
json.JSONDecodeError,
|
| 385 |
) as exc:
|
|
|
|
| 386 |
return {
|
| 387 |
**result,
|
| 388 |
"error": str(exc),
|
|
@@ -506,7 +521,7 @@ def _record_generation_event(payload: Mapping[str, Any]) -> None:
|
|
| 506 |
_capture_posthog_event,
|
| 507 |
"generate_finished",
|
| 508 |
{
|
| 509 |
-
"product":
|
| 510 |
"source": payload.get("source"),
|
| 511 |
"pipeline": payload.get("pipeline"),
|
| 512 |
"tool_name": payload.get("tool_name"),
|
|
@@ -538,7 +553,7 @@ def _record_validation_event(payload: Mapping[str, Any]) -> None:
|
|
| 538 |
_capture_posthog_event,
|
| 539 |
"validation_blocked",
|
| 540 |
{
|
| 541 |
-
"product":
|
| 542 |
"source": payload.get("source"),
|
| 543 |
"pipeline": payload.get("pipeline"),
|
| 544 |
"tool_name": payload.get("tool_name"),
|
|
@@ -569,7 +584,7 @@ def _record_download_event(payload: Mapping[str, Any]) -> None:
|
|
| 569 |
_capture_posthog_event,
|
| 570 |
"download_requested",
|
| 571 |
{
|
| 572 |
-
"product":
|
| 573 |
"source": payload.get("source"),
|
| 574 |
"pipeline": payload.get("pipeline"),
|
| 575 |
"tool_name": payload.get("tool_name"),
|
|
@@ -602,7 +617,7 @@ def _build_generation_payload(
|
|
| 602 |
payload = {
|
| 603 |
"generation_id": generation_id,
|
| 604 |
"timestamp": _utc_now_iso(),
|
| 605 |
-
"product":
|
| 606 |
"source": source,
|
| 607 |
"pipeline": pipeline,
|
| 608 |
"tool_name": tool_name,
|
|
@@ -645,7 +660,7 @@ def _build_download_payload(
|
|
| 645 |
payload = {
|
| 646 |
"generation_id": generation_id or "",
|
| 647 |
"timestamp": _utc_now_iso(),
|
| 648 |
-
"product":
|
| 649 |
"source": source,
|
| 650 |
"pipeline": pipeline or "unknown",
|
| 651 |
"tool_name": tool_name,
|
|
@@ -682,7 +697,7 @@ def _build_validation_payload(
|
|
| 682 |
payload = {
|
| 683 |
"generation_id": generation_id,
|
| 684 |
"timestamp": _utc_now_iso(),
|
| 685 |
-
"product":
|
| 686 |
"source": source,
|
| 687 |
"pipeline": pipeline,
|
| 688 |
"tool_name": tool_name,
|
|
|
|
| 29 |
from huggingface_hub import hf_hub_download
|
| 30 |
from PIL import Image
|
| 31 |
import kornia.color # For RGB→HSV conversion in Stable Cascade filter
|
| 32 |
+
from runtime_config import get_analytics_product
|
| 33 |
|
| 34 |
# ── Export helpers (PNG + embedded SVG download) ──────────────────────────────
|
| 35 |
import base64
|
|
|
|
| 67 |
POSTHOG_API_KEY = os.getenv("POSTHOG_API_KEY", "") or os.getenv(
|
| 68 |
"POSTHOG_SECRET_KEY", ""
|
| 69 |
)
|
| 70 |
+
ANALYTICS_PRODUCT = get_analytics_product()
|
| 71 |
URL_SHORTENER_API_URL = os.getenv("URL_SHORTENER_API_URL", "").rstrip("/")
|
| 72 |
URL_SHORTENER_API_KEY = os.getenv("URL_SHORTENER_API_KEY", "")
|
| 73 |
URL_SHORTENER_SOURCE_APP = os.getenv("URL_SHORTENER_SOURCE_APP", "ai_qr_generator")
|
|
|
|
| 345 |
if input_type != "URL" or not _normalize_bool(use_temporary_short_link):
|
| 346 |
return result
|
| 347 |
if not URL_SHORTENER_API_URL or not URL_SHORTENER_API_KEY:
|
| 348 |
+
print(
|
| 349 |
+
f"[shortener] requested source_app={URL_SHORTENER_SOURCE_APP} configured=false"
|
| 350 |
+
)
|
| 351 |
return {
|
| 352 |
**result,
|
| 353 |
"error": "shortener is not configured on the server",
|
|
|
|
| 360 |
"X-Source-App": URL_SHORTENER_SOURCE_APP,
|
| 361 |
}
|
| 362 |
try:
|
| 363 |
+
print(
|
| 364 |
+
f"[shortener] requested source_app={URL_SHORTENER_SOURCE_APP} original_length={len(str(original_input or ''))}"
|
| 365 |
+
)
|
| 366 |
request_obj = urllib_request.Request(
|
| 367 |
URL_SHORTENER_API_URL,
|
| 368 |
data=request_body,
|
|
|
|
| 376 |
short_url = str(payload.get("short_url") or "").strip()
|
| 377 |
if not short_url:
|
| 378 |
raise ValueError("shortener returned an empty short URL")
|
| 379 |
+
print(
|
| 380 |
+
"[shortener] applied "
|
| 381 |
+
f"source_app={URL_SHORTENER_SOURCE_APP} short_url={short_url} "
|
| 382 |
+
f"existed={bool(payload.get('existed'))} "
|
| 383 |
+
f"reactivated={bool(payload.get('reactivated'))}"
|
| 384 |
+
)
|
| 385 |
return {
|
| 386 |
"applied": True,
|
| 387 |
"effective_qr_text": _normalize_qr_text_for_validation(short_url, "URL"),
|
|
|
|
| 397 |
ValueError,
|
| 398 |
json.JSONDecodeError,
|
| 399 |
) as exc:
|
| 400 |
+
print(f"[shortener] fallback source_app={URL_SHORTENER_SOURCE_APP} error={exc}")
|
| 401 |
return {
|
| 402 |
**result,
|
| 403 |
"error": str(exc),
|
|
|
|
| 521 |
_capture_posthog_event,
|
| 522 |
"generate_finished",
|
| 523 |
{
|
| 524 |
+
"product": ANALYTICS_PRODUCT,
|
| 525 |
"source": payload.get("source"),
|
| 526 |
"pipeline": payload.get("pipeline"),
|
| 527 |
"tool_name": payload.get("tool_name"),
|
|
|
|
| 553 |
_capture_posthog_event,
|
| 554 |
"validation_blocked",
|
| 555 |
{
|
| 556 |
+
"product": ANALYTICS_PRODUCT,
|
| 557 |
"source": payload.get("source"),
|
| 558 |
"pipeline": payload.get("pipeline"),
|
| 559 |
"tool_name": payload.get("tool_name"),
|
|
|
|
| 584 |
_capture_posthog_event,
|
| 585 |
"download_requested",
|
| 586 |
{
|
| 587 |
+
"product": ANALYTICS_PRODUCT,
|
| 588 |
"source": payload.get("source"),
|
| 589 |
"pipeline": payload.get("pipeline"),
|
| 590 |
"tool_name": payload.get("tool_name"),
|
|
|
|
| 617 |
payload = {
|
| 618 |
"generation_id": generation_id,
|
| 619 |
"timestamp": _utc_now_iso(),
|
| 620 |
+
"product": ANALYTICS_PRODUCT,
|
| 621 |
"source": source,
|
| 622 |
"pipeline": pipeline,
|
| 623 |
"tool_name": tool_name,
|
|
|
|
| 660 |
payload = {
|
| 661 |
"generation_id": generation_id or "",
|
| 662 |
"timestamp": _utc_now_iso(),
|
| 663 |
+
"product": ANALYTICS_PRODUCT,
|
| 664 |
"source": source,
|
| 665 |
"pipeline": pipeline or "unknown",
|
| 666 |
"tool_name": tool_name,
|
|
|
|
| 697 |
payload = {
|
| 698 |
"generation_id": generation_id,
|
| 699 |
"timestamp": _utc_now_iso(),
|
| 700 |
+
"product": ANALYTICS_PRODUCT,
|
| 701 |
"source": source,
|
| 702 |
"pipeline": pipeline,
|
| 703 |
"tool_name": tool_name,
|
modal_requirements.txt
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Modal runtime requirements for AI QR service
|
| 2 |
+
comfyui-frontend-package==1.20.5
|
| 3 |
+
comfyui-workflow-templates==0.1.18
|
| 4 |
+
torch
|
| 5 |
+
torchsde
|
| 6 |
+
torchvision
|
| 7 |
+
torchaudio
|
| 8 |
+
numpy>=1.25.0
|
| 9 |
+
einops
|
| 10 |
+
transformers>=4.28.1
|
| 11 |
+
tokenizers>=0.13.3
|
| 12 |
+
sentencepiece
|
| 13 |
+
safetensors>=0.4.2
|
| 14 |
+
aiohttp>=3.11.8
|
| 15 |
+
yarl>=1.18.0
|
| 16 |
+
pyyaml
|
| 17 |
+
Pillow
|
| 18 |
+
scipy
|
| 19 |
+
tqdm
|
| 20 |
+
psutil
|
| 21 |
+
qrcode>=7.1
|
| 22 |
+
spaces
|
| 23 |
+
kornia>=0.7.1
|
| 24 |
+
spandrel
|
| 25 |
+
soundfile
|
| 26 |
+
av>=14.2.0
|
| 27 |
+
pydantic~=2.0
|
| 28 |
+
opencv-python>=4.8.0
|
| 29 |
+
scikit-image==0.25.2
|
| 30 |
+
gradio==5.49.1
|
| 31 |
+
gradio[mcp]
|
| 32 |
+
matplotlib>=3.7.0
|
| 33 |
+
fastapi[standard]
|
| 34 |
+
modal
|
modal_service.py
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import importlib.util
|
| 4 |
+
import os
|
| 5 |
+
import sys
|
| 6 |
+
import time
|
| 7 |
+
from contextlib import asynccontextmanager
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from typing import Any
|
| 10 |
+
|
| 11 |
+
import modal
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
FILE_DIR = Path(__file__).resolve().parent
|
| 15 |
+
for candidate in (FILE_DIR, Path("/root/app")):
|
| 16 |
+
candidate_str = str(candidate)
|
| 17 |
+
if candidate_str not in sys.path:
|
| 18 |
+
sys.path.insert(0, candidate_str)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def _load_support_module(module_name: str):
|
| 22 |
+
for base_dir in (FILE_DIR, Path("/root/app")):
|
| 23 |
+
candidate = base_dir / f"{module_name}.py"
|
| 24 |
+
if not candidate.exists():
|
| 25 |
+
continue
|
| 26 |
+
spec = importlib.util.spec_from_file_location(module_name, candidate)
|
| 27 |
+
if spec is None or spec.loader is None:
|
| 28 |
+
raise ImportError(f"Could not create import spec for {candidate}")
|
| 29 |
+
module = importlib.util.module_from_spec(spec)
|
| 30 |
+
spec.loader.exec_module(module)
|
| 31 |
+
return module
|
| 32 |
+
raise ModuleNotFoundError(module_name)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
try:
|
| 36 |
+
from qr_modal_contract import (
|
| 37 |
+
GenerateRequest,
|
| 38 |
+
build_generation_kwargs,
|
| 39 |
+
build_response_payload,
|
| 40 |
+
consume_final_result,
|
| 41 |
+
resolve_request_seed,
|
| 42 |
+
)
|
| 43 |
+
from qr_modal_loader import load_module_from_file
|
| 44 |
+
from qr_modal_requirements import read_modal_requirements
|
| 45 |
+
except ModuleNotFoundError:
|
| 46 |
+
qr_modal_contract = _load_support_module("qr_modal_contract")
|
| 47 |
+
qr_modal_loader = _load_support_module("qr_modal_loader")
|
| 48 |
+
qr_modal_requirements = _load_support_module("qr_modal_requirements")
|
| 49 |
+
|
| 50 |
+
GenerateRequest = qr_modal_contract.GenerateRequest
|
| 51 |
+
build_generation_kwargs = qr_modal_contract.build_generation_kwargs
|
| 52 |
+
build_response_payload = qr_modal_contract.build_response_payload
|
| 53 |
+
consume_final_result = qr_modal_contract.consume_final_result
|
| 54 |
+
resolve_request_seed = qr_modal_contract.resolve_request_seed
|
| 55 |
+
load_module_from_file = qr_modal_loader.load_module_from_file
|
| 56 |
+
read_modal_requirements = qr_modal_requirements.read_modal_requirements
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
APP_NAME = os.environ.get("MODAL_APP_NAME", "ai-qr-code-generator-api")
|
| 60 |
+
GPU = os.environ.get("MODAL_GPU", "A100-40GB")
|
| 61 |
+
TIMEOUT_SECONDS = int(os.environ.get("MODAL_TIMEOUT_SECONDS", "1800"))
|
| 62 |
+
SCALEDOWN_WINDOW = int(os.environ.get("MODAL_SCALEDOWN_WINDOW", "300"))
|
| 63 |
+
MODEL_CACHE_VOLUME = os.environ.get("MODEL_CACHE_VOLUME", "ai-qr-generator-model-cache")
|
| 64 |
+
|
| 65 |
+
ROOT = Path(__file__).resolve().parent
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def _load_requirements() -> list[str]:
|
| 69 |
+
for requirements_path in (
|
| 70 |
+
ROOT / "modal_requirements.txt",
|
| 71 |
+
Path("/root/app/modal_requirements.txt"),
|
| 72 |
+
):
|
| 73 |
+
if requirements_path.exists():
|
| 74 |
+
return read_modal_requirements(requirements_path)
|
| 75 |
+
raise FileNotFoundError("Could not locate modal_requirements.txt")
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
app = modal.App(APP_NAME)
|
| 79 |
+
volume = modal.Volume.from_name(MODEL_CACHE_VOLUME, create_if_missing=True)
|
| 80 |
+
runtime_secret = modal.Secret.from_name("ai-qr-runtime")
|
| 81 |
+
image = (
|
| 82 |
+
modal.Image.debian_slim(python_version="3.11")
|
| 83 |
+
.apt_install("git", "ffmpeg")
|
| 84 |
+
.pip_install(*_load_requirements())
|
| 85 |
+
.add_local_dir(str(ROOT), remote_path="/root/app")
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
@app.function(
|
| 90 |
+
image=image,
|
| 91 |
+
gpu=GPU,
|
| 92 |
+
cpu=4,
|
| 93 |
+
memory=32768,
|
| 94 |
+
timeout=TIMEOUT_SECONDS,
|
| 95 |
+
scaledown_window=SCALEDOWN_WINDOW,
|
| 96 |
+
max_containers=1,
|
| 97 |
+
volumes={"/root/app/models": volume},
|
| 98 |
+
secrets=[modal.Secret.from_name("huggingface-token"), runtime_secret],
|
| 99 |
+
)
|
| 100 |
+
@modal.asgi_app()
|
| 101 |
+
def api():
|
| 102 |
+
from fastapi import FastAPI, HTTPException
|
| 103 |
+
from fastapi.concurrency import run_in_threadpool
|
| 104 |
+
|
| 105 |
+
state: dict[str, Any] = {
|
| 106 |
+
"backend": None,
|
| 107 |
+
"import_error": None,
|
| 108 |
+
"ready": False,
|
| 109 |
+
}
|
| 110 |
+
|
| 111 |
+
@asynccontextmanager
|
| 112 |
+
async def lifespan(_: FastAPI):
|
| 113 |
+
os.chdir("/root/app")
|
| 114 |
+
os.environ.setdefault("HF_HOME", "/root/app/models/huggingface")
|
| 115 |
+
os.environ.setdefault("TRANSFORMERS_CACHE", "/root/app/models/huggingface")
|
| 116 |
+
os.environ.setdefault("TORCH_HOME", "/root/app/models/torch")
|
| 117 |
+
if "/root/app" not in sys.path:
|
| 118 |
+
sys.path.insert(0, "/root/app")
|
| 119 |
+
try:
|
| 120 |
+
qr_space_app = load_module_from_file("qr_space_entry", "/root/app/app.py")
|
| 121 |
+
state["backend"] = qr_space_app
|
| 122 |
+
state["ready"] = True
|
| 123 |
+
await volume.commit.aio()
|
| 124 |
+
except Exception as exc: # pragma: no cover
|
| 125 |
+
state["import_error"] = repr(exc)
|
| 126 |
+
state["ready"] = False
|
| 127 |
+
yield
|
| 128 |
+
|
| 129 |
+
web_app = FastAPI(title=APP_NAME, lifespan=lifespan)
|
| 130 |
+
|
| 131 |
+
@web_app.get("/health")
|
| 132 |
+
async def health() -> dict[str, Any]:
|
| 133 |
+
return {
|
| 134 |
+
"ok": state["ready"],
|
| 135 |
+
"app_name": APP_NAME,
|
| 136 |
+
"gpu": GPU,
|
| 137 |
+
"scaledown_window": SCALEDOWN_WINDOW,
|
| 138 |
+
"model_cache_volume": MODEL_CACHE_VOLUME,
|
| 139 |
+
"import_error": state["import_error"],
|
| 140 |
+
"analytics_product": os.environ.get("ANALYTICS_PRODUCT", ""),
|
| 141 |
+
"url_shortener_api_url_present": bool(
|
| 142 |
+
os.environ.get("URL_SHORTENER_API_URL")
|
| 143 |
+
),
|
| 144 |
+
"url_shortener_source_app": os.environ.get("URL_SHORTENER_SOURCE_APP", ""),
|
| 145 |
+
"url_shortener_api_key_present": bool(
|
| 146 |
+
os.environ.get("URL_SHORTENER_API_KEY")
|
| 147 |
+
),
|
| 148 |
+
}
|
| 149 |
+
|
| 150 |
+
@web_app.post("/generate")
|
| 151 |
+
async def generate(request: GenerateRequest) -> dict[str, Any]:
|
| 152 |
+
if not state["ready"] or state["backend"] is None:
|
| 153 |
+
raise HTTPException(
|
| 154 |
+
status_code=503, detail=state["import_error"] or "Backend not ready"
|
| 155 |
+
)
|
| 156 |
+
|
| 157 |
+
actual_seed = resolve_request_seed(request)
|
| 158 |
+
prepared_request = request.model_copy(
|
| 159 |
+
update={"seed": actual_seed, "use_custom_seed": True}
|
| 160 |
+
)
|
| 161 |
+
|
| 162 |
+
def _run_generation() -> tuple[Any, str, dict[str, Any] | None]:
|
| 163 |
+
backend = state["backend"]
|
| 164 |
+
kwargs = build_generation_kwargs(prepared_request)
|
| 165 |
+
if prepared_request.mode == "artistic":
|
| 166 |
+
generator = backend.generate_artistic_qr(**kwargs)
|
| 167 |
+
else:
|
| 168 |
+
generator = backend.generate_standard_qr(**kwargs)
|
| 169 |
+
return consume_final_result(generator)
|
| 170 |
+
|
| 171 |
+
started_at = time.perf_counter()
|
| 172 |
+
try:
|
| 173 |
+
image_obj, final_status, settings = await run_in_threadpool(_run_generation)
|
| 174 |
+
except Exception as exc:
|
| 175 |
+
raise HTTPException(status_code=500, detail=str(exc)) from exc
|
| 176 |
+
|
| 177 |
+
elapsed = round(time.perf_counter() - started_at, 3)
|
| 178 |
+
return build_response_payload(
|
| 179 |
+
image_obj,
|
| 180 |
+
final_status,
|
| 181 |
+
request,
|
| 182 |
+
actual_seed=actual_seed,
|
| 183 |
+
elapsed=elapsed,
|
| 184 |
+
settings=settings,
|
| 185 |
+
)
|
| 186 |
+
|
| 187 |
+
return web_app
|
qr_modal_contract.py
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import base64
|
| 4 |
+
import io
|
| 5 |
+
import json
|
| 6 |
+
import random
|
| 7 |
+
from typing import Any, Iterable, Mapping
|
| 8 |
+
|
| 9 |
+
from pydantic import BaseModel, Field
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class GenerateRequest(BaseModel):
|
| 13 |
+
mode: str = Field(default="standard", pattern="^(standard|artistic)$")
|
| 14 |
+
prompt: str = Field(..., min_length=1, max_length=1000)
|
| 15 |
+
qr_text: str = Field(..., min_length=1, max_length=4000)
|
| 16 |
+
input_type: str = Field(default="URL")
|
| 17 |
+
image_size: int = Field(default=512, ge=256, le=1024)
|
| 18 |
+
border_size: int = Field(default=4, ge=0, le=20)
|
| 19 |
+
error_correction: str = Field(default="Medium (15%)")
|
| 20 |
+
module_size: int = Field(default=12, ge=4, le=32)
|
| 21 |
+
module_drawer: str = Field(default="Square")
|
| 22 |
+
use_custom_seed: bool = Field(default=False)
|
| 23 |
+
seed: int = Field(default=0, ge=0, le=2**32 - 1)
|
| 24 |
+
enable_upscale: bool = Field(default=False)
|
| 25 |
+
enable_animation: bool = Field(default=False)
|
| 26 |
+
include_svg: bool = Field(default=False)
|
| 27 |
+
include_image_base64: bool = Field(default=True)
|
| 28 |
+
use_temporary_short_link: bool = Field(default=False)
|
| 29 |
+
analytics_opt_in: bool = Field(default=False)
|
| 30 |
+
negative_prompt: str = Field(
|
| 31 |
+
default=(
|
| 32 |
+
"ugly, tiling, poorly drawn hands, poorly drawn feet, poorly drawn face, "
|
| 33 |
+
"out of frame, extra limbs, body out of frame, blurry, bad anatomy, "
|
| 34 |
+
"blurred, watermark, grainy, signature, cut off, draft, closed eyes, text, logo"
|
| 35 |
+
)
|
| 36 |
+
)
|
| 37 |
+
freeu_b1: float = Field(default=1.4)
|
| 38 |
+
freeu_b2: float = Field(default=1.3)
|
| 39 |
+
freeu_s1: float = Field(default=0.0)
|
| 40 |
+
freeu_s2: float = Field(default=1.3)
|
| 41 |
+
enable_sag: bool = Field(default=True)
|
| 42 |
+
sag_scale: float = Field(default=0.5)
|
| 43 |
+
sag_blur_sigma: float = Field(default=0.5)
|
| 44 |
+
controlnet_strength_first: float = Field(default=0.45)
|
| 45 |
+
controlnet_strength_final: float = Field(default=0.7)
|
| 46 |
+
controlnet_strength_standard_first: float = Field(default=0.45)
|
| 47 |
+
controlnet_strength_standard_final: float = Field(default=1.0)
|
| 48 |
+
enable_color_quantization: bool = Field(default=False)
|
| 49 |
+
num_colors: int = Field(default=4, ge=2, le=4)
|
| 50 |
+
color_1: str = Field(default="#000000")
|
| 51 |
+
color_2: str = Field(default="#FFFFFF")
|
| 52 |
+
color_3: str = Field(default="#FF0000")
|
| 53 |
+
color_4: str = Field(default="#00FF00")
|
| 54 |
+
apply_gradient_filter: bool = Field(default=False)
|
| 55 |
+
gradient_strength: float = Field(default=0.3)
|
| 56 |
+
variation_steps: int = Field(default=5, ge=1, le=10)
|
| 57 |
+
enable_cascade_filter: bool = Field(default=False)
|
| 58 |
+
cascade_blur_kernel: int = Field(default=15)
|
| 59 |
+
cascade_threshold_ratio: float = Field(default=0.33)
|
| 60 |
+
enable_detail_sharpening: bool = Field(default=False)
|
| 61 |
+
sharpening_radius: float = Field(default=2.0)
|
| 62 |
+
sharpening_amount: float = Field(default=1.5)
|
| 63 |
+
sharpening_threshold: int = Field(default=0)
|
| 64 |
+
customize_tile_preprocessing: bool = Field(default=False)
|
| 65 |
+
tile_pyrup_iters: int = Field(default=3, ge=1, le=4)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def build_generation_kwargs(request: GenerateRequest) -> dict[str, Any]:
|
| 69 |
+
return {
|
| 70 |
+
"prompt": request.prompt,
|
| 71 |
+
"negative_prompt": request.negative_prompt,
|
| 72 |
+
"text_input": request.qr_text,
|
| 73 |
+
"input_type": request.input_type,
|
| 74 |
+
"use_temporary_short_link": request.use_temporary_short_link,
|
| 75 |
+
"image_size": request.image_size,
|
| 76 |
+
"border_size": request.border_size,
|
| 77 |
+
"error_correction": request.error_correction,
|
| 78 |
+
"module_size": request.module_size,
|
| 79 |
+
"module_drawer": request.module_drawer,
|
| 80 |
+
"use_custom_seed": request.use_custom_seed,
|
| 81 |
+
"seed": request.seed,
|
| 82 |
+
"enable_upscale": request.enable_upscale,
|
| 83 |
+
"enable_animation": request.enable_animation,
|
| 84 |
+
"include_svg": request.include_svg,
|
| 85 |
+
"analytics_opt_in": request.analytics_opt_in,
|
| 86 |
+
"freeu_b1": request.freeu_b1,
|
| 87 |
+
"freeu_b2": request.freeu_b2,
|
| 88 |
+
"freeu_s1": request.freeu_s1,
|
| 89 |
+
"freeu_s2": request.freeu_s2,
|
| 90 |
+
"enable_sag": request.enable_sag,
|
| 91 |
+
"sag_scale": request.sag_scale,
|
| 92 |
+
"sag_blur_sigma": request.sag_blur_sigma,
|
| 93 |
+
"controlnet_strength_first": request.controlnet_strength_first,
|
| 94 |
+
"controlnet_strength_final": request.controlnet_strength_final,
|
| 95 |
+
"controlnet_strength_standard_first": request.controlnet_strength_standard_first,
|
| 96 |
+
"controlnet_strength_standard_final": request.controlnet_strength_standard_final,
|
| 97 |
+
"enable_color_quantization": request.enable_color_quantization,
|
| 98 |
+
"num_colors": request.num_colors,
|
| 99 |
+
"color_1": request.color_1,
|
| 100 |
+
"color_2": request.color_2,
|
| 101 |
+
"color_3": request.color_3,
|
| 102 |
+
"color_4": request.color_4,
|
| 103 |
+
"apply_gradient_filter": request.apply_gradient_filter,
|
| 104 |
+
"gradient_strength": request.gradient_strength,
|
| 105 |
+
"variation_steps": request.variation_steps,
|
| 106 |
+
"enable_cascade_filter": request.enable_cascade_filter,
|
| 107 |
+
"cascade_blur_kernel": request.cascade_blur_kernel,
|
| 108 |
+
"cascade_threshold_ratio": request.cascade_threshold_ratio,
|
| 109 |
+
"enable_detail_sharpening": request.enable_detail_sharpening,
|
| 110 |
+
"sharpening_radius": request.sharpening_radius,
|
| 111 |
+
"sharpening_amount": request.sharpening_amount,
|
| 112 |
+
"sharpening_threshold": request.sharpening_threshold,
|
| 113 |
+
"customize_tile_preprocessing": request.customize_tile_preprocessing,
|
| 114 |
+
"tile_pyrup_iters": request.tile_pyrup_iters,
|
| 115 |
+
"progress": None,
|
| 116 |
+
"request": None,
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def consume_final_result(
|
| 121 |
+
results: Iterable[Any],
|
| 122 |
+
) -> tuple[Any, str, dict[str, Any] | None]:
|
| 123 |
+
final_image = None
|
| 124 |
+
final_status = ""
|
| 125 |
+
final_settings = None
|
| 126 |
+
for result in results:
|
| 127 |
+
if not isinstance(result, tuple) or len(result) < 2:
|
| 128 |
+
continue
|
| 129 |
+
image = result[0]
|
| 130 |
+
status = result[1]
|
| 131 |
+
if image is not None:
|
| 132 |
+
final_image = image
|
| 133 |
+
final_status = status
|
| 134 |
+
if len(result) >= 3:
|
| 135 |
+
maybe_settings = _extract_settings_dict(result[2])
|
| 136 |
+
if maybe_settings is not None:
|
| 137 |
+
final_settings = maybe_settings
|
| 138 |
+
if final_image is None:
|
| 139 |
+
raise ValueError("Generation finished without producing an image")
|
| 140 |
+
return final_image, final_status, final_settings
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def _extract_settings_dict(value: Any) -> dict[str, Any] | None:
|
| 144 |
+
if isinstance(value, str):
|
| 145 |
+
try:
|
| 146 |
+
parsed = json.loads(value)
|
| 147 |
+
except json.JSONDecodeError:
|
| 148 |
+
return None
|
| 149 |
+
return parsed if isinstance(parsed, dict) else None
|
| 150 |
+
if isinstance(value, Mapping):
|
| 151 |
+
nested = value.get("value")
|
| 152 |
+
if isinstance(nested, str):
|
| 153 |
+
try:
|
| 154 |
+
parsed = json.loads(nested)
|
| 155 |
+
except json.JSONDecodeError:
|
| 156 |
+
return None
|
| 157 |
+
return parsed if isinstance(parsed, dict) else None
|
| 158 |
+
return None
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def encode_image_to_base64_png(image) -> str:
|
| 162 |
+
buffer = io.BytesIO()
|
| 163 |
+
image.convert("RGB").save(buffer, format="PNG")
|
| 164 |
+
return base64.b64encode(buffer.getvalue()).decode("ascii")
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def encode_image_to_embedded_svg(image) -> str:
|
| 168 |
+
png_base64 = encode_image_to_base64_png(image)
|
| 169 |
+
width, height = image.size
|
| 170 |
+
return (
|
| 171 |
+
'<?xml version="1.0" encoding="UTF-8"?>'
|
| 172 |
+
f'<svg xmlns="http://www.w3.org/2000/svg" '
|
| 173 |
+
f'xmlns:xlink="http://www.w3.org/1999/xlink" '
|
| 174 |
+
f'width="{width}" height="{height}" viewBox="0 0 {width} {height}">'
|
| 175 |
+
f"<title>AI QR Code</title>"
|
| 176 |
+
f'<image href="data:image/png;base64,{png_base64}" '
|
| 177 |
+
f'x="0" y="0" width="{width}" height="{height}" '
|
| 178 |
+
f'preserveAspectRatio="xMidYMid meet"/></svg>'
|
| 179 |
+
)
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def resolve_request_seed(request: GenerateRequest, randrange=random.randint) -> int:
|
| 183 |
+
if request.use_custom_seed:
|
| 184 |
+
return request.seed
|
| 185 |
+
return randrange(1, 2**32 - 1)
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def build_response_payload(
|
| 189 |
+
image_obj,
|
| 190 |
+
final_status: str,
|
| 191 |
+
request: GenerateRequest,
|
| 192 |
+
actual_seed: int,
|
| 193 |
+
elapsed: float,
|
| 194 |
+
settings: dict[str, Any] | None = None,
|
| 195 |
+
) -> dict[str, Any]:
|
| 196 |
+
payload = {
|
| 197 |
+
"status": "completed",
|
| 198 |
+
"mode": request.mode,
|
| 199 |
+
"final_status": final_status,
|
| 200 |
+
"seed": actual_seed,
|
| 201 |
+
"image_base64": encode_image_to_base64_png(image_obj)
|
| 202 |
+
if request.include_image_base64
|
| 203 |
+
else None,
|
| 204 |
+
"image_format": "png",
|
| 205 |
+
"svg": encode_image_to_embedded_svg(image_obj) if request.include_svg else None,
|
| 206 |
+
"svg_format": "embedded-png-svg" if request.include_svg else None,
|
| 207 |
+
"width": image_obj.width,
|
| 208 |
+
"height": image_obj.height,
|
| 209 |
+
"duration_seconds": elapsed,
|
| 210 |
+
}
|
| 211 |
+
if settings:
|
| 212 |
+
for key in (
|
| 213 |
+
"use_temporary_short_link",
|
| 214 |
+
"shortener_applied",
|
| 215 |
+
"short_url",
|
| 216 |
+
"shortener_expires_at",
|
| 217 |
+
"shortener_error",
|
| 218 |
+
"effective_qr_text",
|
| 219 |
+
"url_normalization_applied",
|
| 220 |
+
"url_tracking_params_removed",
|
| 221 |
+
"url_chars_saved",
|
| 222 |
+
):
|
| 223 |
+
if key in settings:
|
| 224 |
+
payload[key] = settings[key]
|
| 225 |
+
return payload
|
qr_modal_loader.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import builtins
|
| 4 |
+
import importlib.util
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def load_module_from_file(module_name: str, file_path: str | Path):
|
| 9 |
+
file_path = Path(file_path)
|
| 10 |
+
spec = importlib.util.spec_from_file_location(module_name, file_path)
|
| 11 |
+
if spec is None or spec.loader is None:
|
| 12 |
+
raise ImportError(f"Could not create import spec for {file_path}")
|
| 13 |
+
module = importlib.util.module_from_spec(spec)
|
| 14 |
+
module.__dict__["__builtins__"] = builtins
|
| 15 |
+
spec.loader.exec_module(module)
|
| 16 |
+
return module
|
qr_modal_requirements.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def read_modal_requirements(file_path: str | Path) -> list[str]:
|
| 7 |
+
file_path = Path(file_path)
|
| 8 |
+
values: list[str] = []
|
| 9 |
+
for raw_line in file_path.read_text().splitlines():
|
| 10 |
+
line = raw_line.strip()
|
| 11 |
+
if not line or line.startswith("#"):
|
| 12 |
+
continue
|
| 13 |
+
values.append(line)
|
| 14 |
+
return values
|
runtime_config.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
def get_analytics_product(default: str = "ai_qr_generator") -> str:
|
| 5 |
+
value = os.getenv("ANALYTICS_PRODUCT", default)
|
| 6 |
+
normalized = value.strip()
|
| 7 |
+
return normalized or default
|
tests-unit/modal_service_test/test_qr_modal_contract.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from qr_modal_contract import (
|
| 2 |
+
GenerateRequest,
|
| 3 |
+
build_generation_kwargs,
|
| 4 |
+
consume_final_result,
|
| 5 |
+
resolve_request_seed,
|
| 6 |
+
)
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def test_build_generation_kwargs_includes_short_link_flag_and_wrapper_fields():
|
| 10 |
+
request = GenerateRequest(
|
| 11 |
+
mode="standard",
|
| 12 |
+
prompt="poster",
|
| 13 |
+
qr_text="https://example.com",
|
| 14 |
+
input_type="URL",
|
| 15 |
+
use_temporary_short_link=True,
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
kwargs = build_generation_kwargs(request)
|
| 19 |
+
|
| 20 |
+
assert kwargs["text_input"] == "https://example.com"
|
| 21 |
+
assert kwargs["use_temporary_short_link"] is True
|
| 22 |
+
assert kwargs["analytics_opt_in"] is False
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def test_consume_final_result_supports_wrapper_style_tuples():
|
| 26 |
+
results = [
|
| 27 |
+
(None, "warming", None, None, None),
|
| 28 |
+
(
|
| 29 |
+
"final-image",
|
| 30 |
+
"done",
|
| 31 |
+
{
|
| 32 |
+
"value": '{"shortener_applied": true, "short_url": "https://qrcut.co/demo"}'
|
| 33 |
+
},
|
| 34 |
+
None,
|
| 35 |
+
None,
|
| 36 |
+
),
|
| 37 |
+
]
|
| 38 |
+
|
| 39 |
+
image, status, settings = consume_final_result(results)
|
| 40 |
+
|
| 41 |
+
assert image == "final-image"
|
| 42 |
+
assert status == "done"
|
| 43 |
+
assert settings == {
|
| 44 |
+
"shortener_applied": True,
|
| 45 |
+
"short_url": "https://qrcut.co/demo",
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def test_resolve_request_seed_preserves_custom_seed():
|
| 50 |
+
request = GenerateRequest(
|
| 51 |
+
prompt="poster",
|
| 52 |
+
qr_text="https://example.com",
|
| 53 |
+
use_custom_seed=True,
|
| 54 |
+
seed=123,
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
assert resolve_request_seed(request) == 123
|
tests-unit/utils/runtime_config_test.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
from runtime_config import get_analytics_product
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def test_get_analytics_product_defaults_to_ai_qr_generator(monkeypatch):
|
| 7 |
+
monkeypatch.delenv("ANALYTICS_PRODUCT", raising=False)
|
| 8 |
+
|
| 9 |
+
assert get_analytics_product() == "ai_qr_generator"
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def test_get_analytics_product_uses_env_override(monkeypatch):
|
| 13 |
+
monkeypatch.setenv("ANALYTICS_PRODUCT", "arti_qrcode_app")
|
| 14 |
+
|
| 15 |
+
assert get_analytics_product() == "arti_qrcode_app"
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def test_get_analytics_product_strips_whitespace(monkeypatch):
|
| 19 |
+
monkeypatch.setenv("ANALYTICS_PRODUCT", " arti_qrcode_app ")
|
| 20 |
+
|
| 21 |
+
assert get_analytics_product() == "arti_qrcode_app"
|