Skip to content

Commit c3f6389

Browse files
hipsterusernamepsychedelicious
authored andcommitted
fix ruff and remove unused API route
1 parent 070eef3 commit c3f6389

File tree

3 files changed

+40
-100
lines changed

3 files changed

+40
-100
lines changed

invokeai/app/api/routers/model_manager.py

Lines changed: 2 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -68,14 +68,8 @@ class CacheType(str, Enum):
6868

6969
def add_cover_image_to_model_config(config: AnyModelConfig, dependencies: Type[ApiDependencies]) -> AnyModelConfig:
7070
"""Add a cover image URL to a model configuration."""
71-
# If cover_image is already set and looks like a file path, serve it directly
72-
if config.cover_image and not config.cover_image.startswith('http'):
73-
# This is a file path, so we'll serve it via a special endpoint
74-
config.cover_image = f"/api/v2/models/i/{config.key}/cover_image"
75-
else:
76-
# Try to get from model images service
77-
cover_image = dependencies.invoker.services.model_images.get_url(config.key)
78-
config.cover_image = cover_image
71+
cover_image = dependencies.invoker.services.model_images.get_url(config.key)
72+
config.cover_image = cover_image
7973
return config
8074

8175

@@ -349,58 +343,6 @@ async def get_model_image(
349343
raise HTTPException(status_code=404)
350344

351345

352-
@model_manager_router.get(
353-
"/i/{key}/cover_image",
354-
operation_id="get_model_cover_image",
355-
responses={
356-
200: {
357-
"description": "The model cover image was fetched successfully",
358-
},
359-
400: {"description": "Bad request"},
360-
404: {"description": "The model cover image could not be found"},
361-
},
362-
status_code=200,
363-
)
364-
async def get_model_cover_image(
365-
key: str = Path(description="The key of the model whose cover image to get"),
366-
) -> FileResponse:
367-
"""Gets a cover image file for a model from its stored path"""
368-
369-
try:
370-
# Get the model config to find the cover image path
371-
config = ApiDependencies.invoker.services.model_manager.store.get_model(key)
372-
373-
if not config.cover_image:
374-
raise HTTPException(status_code=404, detail="No cover image found for this model")
375-
376-
# Construct the full path to the image file
377-
models_path = ApiDependencies.invoker.services.configuration.models_path
378-
image_path = models_path / config.cover_image
379-
380-
if not image_path.exists():
381-
raise HTTPException(status_code=404, detail="Cover image file not found")
382-
383-
# Determine the media type based on file extension
384-
media_type = "image/png" # default
385-
if image_path.suffix.lower() in ['.jpg', '.jpeg']:
386-
media_type = "image/jpeg"
387-
elif image_path.suffix.lower() == '.webp':
388-
media_type = "image/webp"
389-
390-
response = FileResponse(
391-
image_path,
392-
media_type=media_type,
393-
filename=image_path.name,
394-
content_disposition_type="inline",
395-
)
396-
response.headers["Cache-Control"] = f"max-age={IMAGE_MAX_AGE}"
397-
return response
398-
except HTTPException:
399-
raise
400-
except Exception as e:
401-
raise HTTPException(status_code=404, detail=f"Error serving cover image: {str(e)}")
402-
403-
404346
@model_manager_router.patch(
405347
"/i/{key}/image",
406348
operation_id="update_model_image",

invokeai/app/services/model_install/model_install_default.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
"""Model installation class."""
22

3-
import json
43
import locale
54
import os
65
import re
@@ -662,7 +661,6 @@ def _probe(self, model_path: Path, config: Optional[ModelRecordChanges] = None):
662661
except InvalidModelConfigException:
663662
return ModelConfigBase.classify(model_path, hash_algo, **fields)
664663

665-
666664
def _register(
667665
self, model_path: Path, config: Optional[ModelRecordChanges] = None, info: Optional[AnyModelConfig] = None
668666
) -> str:
Lines changed: 38 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -1,46 +1,48 @@
11
"""Utility functions for extracting metadata from LoRA model files."""
22

33
import json
4-
from pathlib import Path
5-
from typing import Dict, Any, Optional, Set, Tuple
64
import logging
5+
from pathlib import Path
6+
from typing import Any, Dict, Optional, Set, Tuple
77

88
from PIL import Image
99

10-
from invokeai.backend.model_manager.config import AnyModelConfig, ModelType
1110
from invokeai.app.util.thumbnails import make_thumbnail
11+
from invokeai.backend.model_manager.config import AnyModelConfig, ModelType
1212

1313
logger = logging.getLogger(__name__)
1414

1515

16-
def extract_lora_metadata(model_path: Path, model_key: str, model_images_path: Path) -> Tuple[Optional[str], Optional[Set[str]]]:
16+
def extract_lora_metadata(
17+
model_path: Path, model_key: str, model_images_path: Path
18+
) -> Tuple[Optional[str], Optional[Set[str]]]:
1719
"""
1820
Extract metadata for a LoRA model from associated JSON and image files.
19-
21+
2022
Args:
2123
model_path: Path to the LoRA model file
2224
model_key: Unique key for the model
2325
model_images_path: Path to the model images directory
24-
26+
2527
Returns:
2628
Tuple of (description, trigger_phrases)
2729
"""
2830
model_stem = model_path.stem
2931
model_dir = model_path.parent
30-
32+
3133
# Find and process preview image
3234
_process_preview_image(model_stem, model_dir, model_key, model_images_path)
33-
35+
3436
# Extract metadata from JSON
3537
description, trigger_phrases = _extract_json_metadata(model_stem, model_dir)
36-
38+
3739
return description, trigger_phrases
3840

3941

4042
def _process_preview_image(model_stem: str, model_dir: Path, model_key: str, model_images_path: Path) -> bool:
4143
"""Find and process a preview image for the model, saving it to the model images store."""
42-
image_extensions = ['.png', '.jpg', '.jpeg', '.webp']
43-
44+
image_extensions = [".png", ".jpg", ".jpeg", ".webp"]
45+
4446
for ext in image_extensions:
4547
image_path = model_dir / f"{model_stem}{ext}"
4648
if image_path.exists():
@@ -51,39 +53,39 @@ def _process_preview_image(model_stem: str, model_dir: Path, model_key: str, mod
5153
thumbnail = make_thumbnail(img, 256)
5254
thumbnail_path = model_images_path / f"{model_key}.webp"
5355
thumbnail.save(thumbnail_path, format="webp")
54-
56+
5557
logger.info(f"Processed preview image {image_path.name} for model {model_key}")
5658
return True
57-
59+
5860
except Exception as e:
5961
logger.warning(f"Failed to process preview image {image_path.name}: {e}")
6062
return False
61-
63+
6264
return False
6365

6466

6567
def _extract_json_metadata(model_stem: str, model_dir: Path) -> Tuple[Optional[str], Optional[Set[str]]]:
6668
"""Extract metadata from a JSON file with the same name as the model."""
6769
json_path = model_dir / f"{model_stem}.json"
68-
70+
6971
if not json_path.exists():
7072
return None, None
71-
73+
7274
try:
73-
with open(json_path, 'r', encoding='utf-8') as f:
75+
with open(json_path, "r", encoding="utf-8") as f:
7476
metadata = json.load(f)
75-
77+
7678
# Extract description
7779
description = _build_description(metadata)
78-
80+
7981
# Extract trigger phrases
8082
trigger_phrases = _extract_trigger_phrases(metadata)
81-
83+
8284
if description or trigger_phrases:
8385
logger.info(f"Applied metadata from {json_path.name}")
84-
86+
8587
return description, trigger_phrases
86-
88+
8789
except (json.JSONDecodeError, IOError, Exception) as e:
8890
logger.warning(f"Failed to read metadata from {json_path}: {e}")
8991
return None, None
@@ -92,35 +94,35 @@ def _extract_json_metadata(model_stem: str, model_dir: Path) -> Tuple[Optional[s
9294
def _build_description(metadata: Dict[str, Any]) -> Optional[str]:
9395
"""Build a description from metadata fields."""
9496
description_parts = []
95-
97+
9698
if description := metadata.get("description"):
9799
description_parts.append(str(description).strip())
98-
100+
99101
if notes := metadata.get("notes"):
100102
description_parts.append(str(notes).strip())
101-
103+
102104
return " | ".join(description_parts) if description_parts else None
103105

104106

105107
def _extract_trigger_phrases(metadata: Dict[str, Any]) -> Optional[Set[str]]:
106108
"""Extract trigger phrases from metadata."""
107109
if not (activation_text := metadata.get("activation text")):
108110
return None
109-
111+
110112
activation_text = str(activation_text).strip()
111113
if not activation_text:
112114
return None
113-
115+
114116
# Split on commas and clean up each phrase
115-
phrases = [phrase.strip() for phrase in activation_text.split(',') if phrase.strip()]
116-
117+
phrases = [phrase.strip() for phrase in activation_text.split(",") if phrase.strip()]
118+
117119
return set(phrases) if phrases else None
118120

119121

120122
def apply_lora_metadata(info: AnyModelConfig, model_path: Path, model_images_path: Path) -> None:
121123
"""
122124
Apply extracted metadata to a LoRA model configuration.
123-
125+
124126
Args:
125127
info: The model configuration to update
126128
model_path: Path to the LoRA model file
@@ -129,17 +131,15 @@ def apply_lora_metadata(info: AnyModelConfig, model_path: Path, model_images_pat
129131
# Only process LoRA models
130132
if info.type != ModelType.LoRA:
131133
return
132-
134+
133135
# Extract and apply metadata
134-
description, trigger_phrases = extract_lora_metadata(
135-
model_path, info.key, model_images_path
136-
)
137-
136+
description, trigger_phrases = extract_lora_metadata(model_path, info.key, model_images_path)
137+
138138
# We don't set cover_image path in the config anymore since images are stored
139139
# separately in the model images store by model key
140-
140+
141141
if description:
142142
info.description = description
143-
143+
144144
if trigger_phrases:
145-
info.trigger_phrases = trigger_phrases
145+
info.trigger_phrases = trigger_phrases

0 commit comments

Comments
 (0)