feat(lora): make tags only from short trigger phrases (#618)
A trained-words entry becomes a tag only when it is one short clean phrase: the existing tag rule (at most 50 characters, no control character), no ASCII or fullwidth comma, no <...> model call and no prompt weight. The trigger-word lookup still sees every entry. The import review gains a Trigger words row (N become tags, M not made tags) and the import job logs how many entries were not made tags.
This commit is contained in:
@@ -6,9 +6,12 @@ current imports, those a saved pair uses and the example images an import
|
||||
would download. It writes nothing and requests nothing. It answers a
|
||||
``Plan`` (the maintenance plan's shape, ``py/api/maintenance.py``) plus
|
||||
``{lora_files, with_metadata, skipped, with_local_media, current_imports,
|
||||
blocked_by_pairs, planned_downloads, network:{planned_downloads, api_key},
|
||||
layout}`` (#355: ``layout`` says which LoraManager settings file, storage mode
|
||||
and library the import read, and ``error`` when they cannot be used). A plan
|
||||
blocked_by_pairs, planned_downloads, trigger_tags, trigger_not_tags,
|
||||
network:{planned_downloads, api_key}, layout}`` (#355: ``layout`` says which
|
||||
LoraManager settings file, storage mode and library the import read, and
|
||||
``error`` when they cannot be used; #618: ``trigger_tags`` and
|
||||
``trigger_not_tags`` count the trained-words entries that become tags and
|
||||
those that are lists or sentences, which the job log repeats). A plan
|
||||
that saved pairs block, or whose layout is unusable, carries no token
|
||||
(nothing can be applied).
|
||||
|
||||
@@ -104,6 +107,13 @@ def _import_line(result, skipped):
|
||||
return " · ".join(parts)
|
||||
|
||||
|
||||
def not_tags_line(count):
|
||||
"""The job log's count of trained-words entries not made tags (#618)."""
|
||||
entries = _count(count, "trained-words entry", "trained-words entries")
|
||||
verb = "was" if count == 1 else "were"
|
||||
return f"{entries} {verb} not made tags (lists or sentences)"
|
||||
|
||||
|
||||
def _all_downloads_failed(errors):
|
||||
"""The warning when every planned download failed (#337)."""
|
||||
if errors == 1:
|
||||
@@ -315,6 +325,8 @@ class LoraImportRoutesMixin:
|
||||
"current_imports": current,
|
||||
"blocked_by_pairs": blocked,
|
||||
"planned_downloads": downloads,
|
||||
"trigger_tags": int(found.get("trigger_tags", 0)),
|
||||
"trigger_not_tags": int(found.get("trigger_not_tags", 0)),
|
||||
"scope": {
|
||||
"count": found["with_metadata"],
|
||||
"label": (
|
||||
@@ -441,6 +453,9 @@ class LoraImportRoutesMixin:
|
||||
self.logger.exception("LoRA import staging failed")
|
||||
return _fail_job(job, "import-failed", f"{FAILED} {CACHE_NOTE}")
|
||||
self._count_downloads(job, staged)
|
||||
not_tags = staged.stats.get("trigger_not_tags", 0)
|
||||
if not_tags:
|
||||
job.log_line(not_tags_line(not_tags))
|
||||
# M4: what staging skipped stays on the job whatever happens next.
|
||||
job.record_counted(
|
||||
"skipped",
|
||||
|
||||
+27
-9
@@ -111,23 +111,29 @@ def preview(
|
||||
"""The review's counts (blocking; reads only, requests nothing).
|
||||
|
||||
``{lora_files, with_metadata, skipped, with_local_media,
|
||||
planned_downloads, fingerprint, names, layout}``: the metadata files
|
||||
seen, the kept LoRAs whose sidecar parses, the rest, the LoRAs with a
|
||||
local image, the CivitAI images an import would download for the LoRAs
|
||||
without one (not yet in the cache), the first LoRA names and what the
|
||||
layout says (``layout_summary``).
|
||||
planned_downloads, trigger_tags, trigger_not_tags, fingerprint, names,
|
||||
layout}``: the metadata files seen, the kept LoRAs whose sidecar parses,
|
||||
the rest, the LoRAs with a local image, the CivitAI images an import would
|
||||
download for the LoRAs without one (not yet in the cache), the trained-words
|
||||
entries that become tags and those that do not (#618), the first LoRA
|
||||
names and what the layout says (``layout_summary``).
|
||||
"""
|
||||
discovery = discover(lora_manager_path)
|
||||
layout = discovery.layout
|
||||
with_metadata = 0
|
||||
with_local_media = 0
|
||||
planned = 0
|
||||
trigger_tags = 0
|
||||
trigger_not_tags = 0
|
||||
names = []
|
||||
for sidecar in discovery.sidecars:
|
||||
metadata = lora_utils.read_lora_metadata(sidecar.metadata_path)
|
||||
if not metadata:
|
||||
continue
|
||||
with_metadata += 1
|
||||
words, not_tags = lora_utils.trigger_word_tags(metadata)
|
||||
trigger_tags += len(words)
|
||||
trigger_not_tags += not_tags
|
||||
if local_media(sidecar, metadata, layout, media_extensions):
|
||||
with_local_media += 1
|
||||
else:
|
||||
@@ -142,6 +148,8 @@ def preview(
|
||||
"skipped": discovery.scanned - with_metadata,
|
||||
"with_local_media": with_local_media,
|
||||
"planned_downloads": planned,
|
||||
"trigger_tags": trigger_tags,
|
||||
"trigger_not_tags": trigger_not_tags,
|
||||
"fingerprint": fingerprint(discovery),
|
||||
"names": names,
|
||||
"layout": layout_summary(layout, Path.home()),
|
||||
@@ -149,17 +157,22 @@ def preview(
|
||||
|
||||
|
||||
def build_record(metadata: Dict, path: Path, images: List[str]) -> Dict:
|
||||
"""The prompt a LoRA becomes: its example prompt (else its name), tags, images."""
|
||||
"""The prompt a LoRA becomes: its example prompt (else its name), tags, images.
|
||||
|
||||
Only the trained words that are one short clean phrase become tags
|
||||
(#618, ``lora_utils.is_tag_phrase``); ``trigger_not_tags`` counts the rest.
|
||||
"""
|
||||
model_name = lora_utils.get_model_name_from_metadata(metadata)
|
||||
text = lora_utils.get_example_prompt_from_metadata(metadata) or model_name
|
||||
tags = ["lora-manager", f"lora:{model_name}"]
|
||||
tags.extend(lora_utils.get_trigger_words_from_metadata(metadata))
|
||||
words, not_tags = lora_utils.trigger_word_tags(metadata)
|
||||
tags = ["lora-manager", f"lora:{model_name}", *words]
|
||||
return {
|
||||
"name": model_name,
|
||||
"text": text,
|
||||
"hash": generate_prompt_hash(text),
|
||||
"tags": list(dict.fromkeys(tags)),
|
||||
"images": images,
|
||||
"trigger_not_tags": not_tags,
|
||||
}
|
||||
|
||||
|
||||
@@ -171,7 +184,11 @@ class StagedImport:
|
||||
records: List[Dict] = field(default_factory=list)
|
||||
skipped: List[str] = field(default_factory=list)
|
||||
stats: Dict[str, int] = field(
|
||||
default_factory=lambda: {"downloaded": 0, "download_errors": 0}
|
||||
default_factory=lambda: {
|
||||
"downloaded": 0,
|
||||
"download_errors": 0,
|
||||
"trigger_not_tags": 0,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@@ -219,6 +236,7 @@ def stage(
|
||||
images = list(dict.fromkeys([*local, *remote]))
|
||||
record = build_record(metadata, path, images)
|
||||
staged.records.append(record)
|
||||
staged.stats["trigger_not_tags"] += record["trigger_not_tags"]
|
||||
except Exception as error: # one LoRA never stops the import
|
||||
name = lora_utils.get_model_name_from_metadata(metadata)
|
||||
if logger is not None:
|
||||
|
||||
@@ -22,11 +22,13 @@ from urllib.parse import urljoin, urlsplit
|
||||
|
||||
try:
|
||||
from ..utils.logging_config import get_logger
|
||||
from ..utils.validators import validate_tags
|
||||
except ImportError:
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
from utils.logging_config import get_logger
|
||||
from utils.validators import validate_tags
|
||||
|
||||
from dataclasses import replace
|
||||
|
||||
@@ -387,6 +389,44 @@ def get_trigger_words_from_metadata(metadata: Dict) -> List[str]:
|
||||
return []
|
||||
|
||||
|
||||
# #618: what a prompt weight looks like, ``(masterpiece:1.2)``: an instruction
|
||||
# to the sampler, never a label.
|
||||
_PROMPT_WEIGHT = re.compile(r"\([^()]*:\s*-?\d*\.?\d+\s*\)")
|
||||
# The ASCII and the fullwidth comma: an entry holding either is a list.
|
||||
_COMMAS = (",", ",")
|
||||
|
||||
|
||||
def is_tag_phrase(entry: object) -> bool:
|
||||
"""Whether a trained-words entry is one short clean phrase (#618, Option A).
|
||||
|
||||
The existing tag rule (``validate_tags``: not empty, at most 50
|
||||
characters, no control character), and no comma (ASCII or fullwidth), no
|
||||
``<``/``>`` (``<lora:name:0.8>`` loads a model) and no prompt weight.
|
||||
Plain parentheses stay allowed (``hatsune miku (vocaloid)``).
|
||||
"""
|
||||
if not isinstance(entry, str):
|
||||
return False
|
||||
phrase = entry.strip()
|
||||
try:
|
||||
validate_tags([phrase])
|
||||
except ValueError:
|
||||
return False
|
||||
if any(comma in phrase for comma in _COMMAS):
|
||||
return False
|
||||
if "<" in phrase or ">" in phrase:
|
||||
return False
|
||||
return _PROMPT_WEIGHT.search(phrase) is None
|
||||
|
||||
|
||||
def trigger_word_tags(metadata: Dict) -> Tuple[List[str], int]:
|
||||
"""``(tags, not_tags)``: the trigger words that are tag phrases, stripped
|
||||
and in order, and how many were not (#618). The trigger-word lookup
|
||||
(``get_trigger_words_from_metadata``) still sees every entry."""
|
||||
words = get_trigger_words_from_metadata(metadata)
|
||||
tags = [word for word in words if is_tag_phrase(word)]
|
||||
return tags, len(words) - len(tags)
|
||||
|
||||
|
||||
def get_example_prompt_from_metadata(metadata: Dict) -> Optional[str]:
|
||||
"""Extract an example prompt from civitai image metadata.
|
||||
|
||||
|
||||
@@ -261,7 +261,8 @@ function measureReview() {
|
||||
|
||||
/**
|
||||
* D107: the server's import plan in the concept's review: "Review LoRA import" with "LoRA reference data" as its `h3`,
|
||||
* the concept's four rows with the plan's values plus Found and Network, the LoRAs it found (`details`), the hold
|
||||
* the concept's four rows with the plan's values plus Found, Trigger words (#618, D210) and Network, the LoRAs it
|
||||
* found (`details`), the hold
|
||||
* line with the cache sentence in the concept's `p.small`, the D55 backup box, and Cancel / "Start import".
|
||||
*/
|
||||
function mapImportConcept(reference, plan) {
|
||||
@@ -273,6 +274,7 @@ function mapImportConcept(reference, plan) {
|
||||
heading: { ...reference.heading, text: 'LoRA reference data' },
|
||||
grid: { ...reference.grid, rows: [['LoraManager', 'environment settings · alongside storage · library default'],
|
||||
['Scope', plan.scope.label], ['Found', '2 metadata files · 2 LoRAs · 0 with local images'],
|
||||
['Trigger words', '2 become tags'],
|
||||
['Protected', 'Nothing is protected'], ['Network', 'Downloads up to 2 example images from CivitAI'],
|
||||
['Backup', `Create and verify before changes (${plan.backup.destination_label})`],
|
||||
['Media on disk', 'No files are removed; image links are replaced']] },
|
||||
@@ -333,9 +335,10 @@ test('LoRA import review comparison detects mutations', async ({ page, request }
|
||||
const expected = mapImportConcept(concept, plan);
|
||||
const paths = async () => diffInventory(expected, await page.evaluate(measureReview)).map(item => item.path);
|
||||
expect(await paths()).toEqual([]);
|
||||
await page.evaluate(() => { document.querySelectorAll('dialog#modal[open] dl.meta-grid dt')[4].textContent = 'Downloads'; });
|
||||
expect(await paths()).toEqual(['grid.rows.4.0']);
|
||||
await page.evaluate(() => { document.querySelectorAll('dialog#modal[open] dl.meta-grid dt')[4].textContent = 'Network'; });
|
||||
// Network is the sixth row (after #618's Trigger words).
|
||||
await page.evaluate(() => { document.querySelectorAll('dialog#modal[open] dl.meta-grid dt')[5].textContent = 'Downloads'; });
|
||||
expect(await paths()).toEqual(['grid.rows.5.0']);
|
||||
await page.evaluate(() => { document.querySelectorAll('dialog#modal[open] dl.meta-grid dt')[5].textContent = 'Network'; });
|
||||
const undoGrid = await mutate(page, { css: 'dialog#modal dl.meta-grid { column-gap: 3px; }' });
|
||||
expect(await paths()).toEqual(expect.arrayContaining(['grid.columnGap']));
|
||||
await undoGrid();
|
||||
|
||||
@@ -343,6 +343,7 @@ test('Review import shows replacement, blocked items and network effects with th
|
||||
['LoraManager', 'environment settings · alongside storage · library default'],
|
||||
['Scope', 'Replace 2 imported prompts with 3 LoRAs'],
|
||||
['Found', '3 metadata files · 3 LoRAs · 0 with local images'],
|
||||
['Trigger words', '3 become tags'],
|
||||
['Protected', 'Nothing is protected'],
|
||||
['Network', 'Downloads up to 3 example images from CivitAI'],
|
||||
['Backup', 'Create and verify before changes (browser.db.backup_<date and time>)'],
|
||||
@@ -387,7 +388,8 @@ test('saved pairs block the import: the review explains it and offers only Close
|
||||
await enable(page);
|
||||
await layoutOf(page).getByRole('button', { name: 'Review import', exact: true }).click();
|
||||
// gridOf reads once; poll until the review has rendered its rows.
|
||||
await expect.poll(async () => (await gridOf(page))[3]).toEqual(['Protected', '1 imported prompt used by saved pairs']);
|
||||
await expect.poll(async () => (await gridOf(page)).find(([term]) => term === 'Protected'))
|
||||
.toEqual(['Protected', '1 imported prompt used by saved pairs']);
|
||||
await expect(dialog(page).locator('p.small')).toHaveText(
|
||||
'Delete or change the saved pairs that use these prompts, then review the import again. Nothing was changed.');
|
||||
expect(await dialog(page).locator('.dialog-actions button').allTextContents()).toEqual(['Close']);
|
||||
@@ -395,6 +397,18 @@ test('saved pairs block the import: the review explains it and offers only Close
|
||||
await expect(dialog(page)).toHaveCount(0);
|
||||
});
|
||||
|
||||
test('the import review counts the trained words that are lists or sentences and not made tags (#618)',
|
||||
async ({ page, request }) => {
|
||||
await lora(request, { loras: 2, junk: true });
|
||||
await openIntegrations(page);
|
||||
await enable(page);
|
||||
await layoutOf(page).getByRole('button', { name: 'Review import', exact: true }).click();
|
||||
await expect.poll(async () => (await gridOf(page)).find(([term]) => term === 'Trigger words'))
|
||||
.toEqual(['Trigger words', '2 become tags · 4 not made tags (lists or sentences)']);
|
||||
await dialog(page).getByRole('button', { name: 'Cancel', exact: true }).click();
|
||||
await expect(dialog(page)).toHaveCount(0);
|
||||
});
|
||||
|
||||
test('unusable LoraManager settings: the review says why and offers only Close (#355)', async ({ page, request }) => {
|
||||
await lora(request, { previous: 1, settings: 'invalid' });
|
||||
await openIntegrations(page);
|
||||
|
||||
@@ -8,7 +8,7 @@ reaches a real LoraManager, ComfyUI install or the network:
|
||||
the image cache, forgets every LoRA import and injected failure, and opens
|
||||
the download gate;
|
||||
- ``POST /__test__/integrations/lora-manager``
|
||||
``{loras, civitai, preview, previous, settings}`` writes
|
||||
``{loras, civitai, preview, previous, settings, junk}`` writes
|
||||
``custom_nodes/ComfyUI-Lora-Manager`` (detected through the
|
||||
``folder_paths`` stub's base path) and ``loras`` LoRAs under
|
||||
``models/loras``: each a ``<stem>.safetensors`` model beside its
|
||||
@@ -18,7 +18,9 @@ reaches a real LoraManager, ComfyUI install or the network:
|
||||
downloads it only for a LoRA without a local preview); ``previous`` saves
|
||||
that many earlier ``lora-manager`` imports with tags and image links;
|
||||
``settings: "invalid"`` makes LoraManager's settings file unreadable JSON
|
||||
(the server's own isolated settings folder, ``LORA_MANAGER_SETTINGS_DIR``);
|
||||
(the server's own isolated settings folder, ``LORA_MANAGER_SETTINGS_DIR``); ``junk``
|
||||
adds a comma list and a ``<lora:…>`` call to each LoRA's trained words, which
|
||||
the import does not make tags (#618);
|
||||
- ``POST /__test__/integrations/gate`` ``{hold}`` holds every CivitAI
|
||||
download until it is released (``{"hold": false}``), so a test sees the job
|
||||
while it downloads;
|
||||
@@ -145,6 +147,9 @@ def register_integrations_commands(app, routes, api, root: Path):
|
||||
for number in range(count):
|
||||
stem = f"style_{number + 1:02}"
|
||||
civitai = {"trainedWords": [f"trigger{number + 1}"]}
|
||||
if data.get("junk") is True:
|
||||
# #618: a comma list and a model call, never made tags.
|
||||
civitai["trainedWords"] += ["score_9, score_8_up,", "<lora:x:0.8>"]
|
||||
if data.get("civitai") is True:
|
||||
civitai["images"] = [
|
||||
{
|
||||
|
||||
@@ -137,6 +137,23 @@ test('the import review shows replacement, blocked items and network effects (D1
|
||||
['Found', '1 metadata file · 1 LoRA · 0 with local images']);
|
||||
});
|
||||
|
||||
test('the import review counts the trained words not made tags, after Found (#618)', async () => {
|
||||
const { importGrid } = await integrations;
|
||||
const rowAfterFound = plan => {
|
||||
const rows = importGrid(plan);
|
||||
const at = rows.findIndex(([term]) => term === 'Found');
|
||||
return rows[at + 1];
|
||||
};
|
||||
assert.deepEqual(rowAfterFound({ trigger_tags: 1204, trigger_not_tags: 232 }),
|
||||
['Trigger words', '1,204 become tags · 232 not made tags (lists or sentences)']);
|
||||
assert.deepEqual(rowAfterFound({ trigger_tags: 3, trigger_not_tags: 0 }), ['Trigger words', '3 become tags']);
|
||||
assert.deepEqual(rowAfterFound({ trigger_tags: 0, trigger_not_tags: 1 }),
|
||||
['Trigger words', '0 become tags · 1 not made tags (lists or sentences)']);
|
||||
// Neither number above 0 (or missing, as from an older server): no row.
|
||||
assert.deepEqual(rowAfterFound({ trigger_tags: 0, trigger_not_tags: 0 })[0], 'Protected');
|
||||
assert.deepEqual(rowAfterFound({ trigger_tags: '5', trigger_not_tags: -1 })[0], 'Protected');
|
||||
});
|
||||
|
||||
test('the LoraManager row names what the import read, and an unusable layout closes the review (#355)', async () => {
|
||||
const { layoutText, closeNote, LAYOUT_UNUSABLE, BLOCKED_NOTE, NOTHING_TO_IMPORT } = await integrations;
|
||||
assert.equal(layoutText({ source: 'environment', mode: 'alongside', library: 'default', error: null }),
|
||||
|
||||
@@ -537,6 +537,32 @@ class LoraImportRouteTests(LoraImportAPITestCase):
|
||||
resp, body = await self._post(APPLY, {"token": plan["token"]})
|
||||
self.assertEqual((resp.status, body["code"]), (409, "plan-used"))
|
||||
|
||||
async def test_preview_and_job_say_how_many_entries_were_not_made_tags(self):
|
||||
# #618: the review and the job log count the trained-words entries
|
||||
# that were lists or sentences.
|
||||
_write_metadata(self.loras, "neon", words=["glow", "a, b, c", "<lora:x:1>"])
|
||||
(self.loras / "neon.png").write_bytes(_png_bytes())
|
||||
resp, plan = await self._post(PREVIEW)
|
||||
self.assertEqual(resp.status, 200, plan)
|
||||
self.assertEqual((plan["trigger_tags"], plan["trigger_not_tags"]), (1, 2))
|
||||
|
||||
resp, body = await self._post(APPLY, {"token": plan["token"]})
|
||||
self.assertEqual(resp.status, 202, body)
|
||||
job = self.api._jobs.get(body["job"]["id"])
|
||||
await job.task
|
||||
self.assertEqual(job.state, "finished", job.log)
|
||||
line = "2 trained-words entries were not made tags (lists or sentences)"
|
||||
self.assertTrue(any(entry.endswith(line) for entry in job.log), job.log)
|
||||
neon = self.api.db.search_prompts(category=CATEGORY)[0]
|
||||
self.assertEqual(sorted(neon["tags"]), ["glow", "lora-manager", "lora:neon"])
|
||||
|
||||
async def test_job_log_is_silent_when_every_entry_is_a_tag(self):
|
||||
self._two_loras()
|
||||
_plan, job = await self._apply_reviewed()
|
||||
await job.task
|
||||
self.assertEqual(job.state, "finished", job.log)
|
||||
self.assertFalse(any("not made tags" in line for line in job.log), job.log)
|
||||
|
||||
async def test_a_finished_import_clears_the_layout_cache(self):
|
||||
# #362: the import may link files under a folder LoraManager created
|
||||
# after the image routes cached its layout.
|
||||
@@ -1446,10 +1472,40 @@ class LoraImportStageTests(unittest.TestCase):
|
||||
"hash": generate_prompt_hash("neon street"),
|
||||
"tags": ["lora-manager", "lora:neon", "glow"],
|
||||
"images": [os.path.realpath(self.loras / "neon.png")],
|
||||
"trigger_not_tags": 0,
|
||||
}
|
||||
],
|
||||
)
|
||||
|
||||
# #618: only one short clean phrase becomes a tag.
|
||||
|
||||
def test_build_record_makes_tags_only_from_short_phrases(self):
|
||||
metadata = {
|
||||
"file_name": "neon.safetensors",
|
||||
"model_name": "neon",
|
||||
"civitai": {"trainedWords": ["neon", "a, b, c", "<lora:x:1>"]},
|
||||
}
|
||||
record = lora_import.build_record(metadata, self.loras / "neon.json", [])
|
||||
self.assertEqual(record["tags"], ["lora-manager", "lora:neon", "neon"])
|
||||
self.assertEqual(record["trigger_not_tags"], 2)
|
||||
|
||||
def test_stage_counts_entries_not_made_tags(self):
|
||||
_write_metadata(self.loras, "one", words=["glow", "a, b", "<lora:x:1>"])
|
||||
_write_metadata(self.loras, "two", words=["long, comma, list"])
|
||||
_write_metadata(self.loras, "three", words=["fine"])
|
||||
staged = lora_import.stage(self.discover(), self.tmp, media_extensions=MEDIA)
|
||||
self.assertEqual(staged.stats["trigger_not_tags"], 3)
|
||||
tags = {r["name"]: r["tags"] for r in staged.records}
|
||||
self.assertEqual(tags["one"], ["lora-manager", "lora:one", "glow"])
|
||||
self.assertEqual(tags["two"], ["lora-manager", "lora:two"])
|
||||
|
||||
def test_preview_sums_trigger_tags_and_not_tags(self):
|
||||
_write_metadata(self.loras, "one", words=["glow", "a, b", "(x:1.2)"])
|
||||
_write_metadata(self.loras, "two", words=["neon", "street"])
|
||||
_write_metadata(self.loras, "none")
|
||||
found = lora_import.preview(str(self.lm), self.tmp / "cache", MEDIA)
|
||||
self.assertEqual((found["trigger_tags"], found["trigger_not_tags"]), (3, 2))
|
||||
|
||||
def test_preview_counts_local_media_and_downloads(self):
|
||||
_write_metadata(self.loras, "local", images=["https://civitai.com/l.png"])
|
||||
(self.loras / "local.webp").write_bytes(b"x")
|
||||
|
||||
@@ -99,6 +99,64 @@ class TestGetTriggerWords(unittest.TestCase):
|
||||
self.assertEqual(get_trigger_words_from_metadata(meta), ["valid", "also_valid"])
|
||||
|
||||
|
||||
class TestTriggerWordTags(unittest.TestCase):
|
||||
"""#618: a trained-words entry becomes a tag only when it is one short
|
||||
clean phrase (Option A); the trigger-word lookup keeps every entry."""
|
||||
|
||||
KEPT = [
|
||||
"neon glow",
|
||||
" ohwx woman ",
|
||||
"score_9",
|
||||
"hatsune miku (vocaloid)",
|
||||
"hatsune miku \\(vocaloid\\)",
|
||||
"a" * 50,
|
||||
]
|
||||
SKIPPED = [
|
||||
"a" * 51,
|
||||
"score_9, score_8_up, realistic,",
|
||||
"realistic,",
|
||||
"赛博朋克,霓虹",
|
||||
"line one\nline two",
|
||||
"tab\tword",
|
||||
"<lora:neon:0.8>",
|
||||
"(masterpiece:1.2)",
|
||||
"a girl (smile:0.8) outdoors",
|
||||
"ratio (16:9)",
|
||||
]
|
||||
|
||||
def test_short_clean_phrases_are_tags(self):
|
||||
for entry in self.KEPT:
|
||||
with self.subTest(entry=entry):
|
||||
self.assertTrue(lora_utils.is_tag_phrase(entry))
|
||||
|
||||
def test_lists_sentences_and_prompt_syntax_are_not(self):
|
||||
for entry in self.SKIPPED:
|
||||
with self.subTest(entry=entry):
|
||||
self.assertFalse(lora_utils.is_tag_phrase(entry))
|
||||
|
||||
def test_non_entries_are_not_phrases(self):
|
||||
for entry in ("", " ", None, 12):
|
||||
with self.subTest(entry=entry):
|
||||
self.assertFalse(lora_utils.is_tag_phrase(entry))
|
||||
|
||||
def test_trigger_word_tags_keeps_order_strips_and_counts(self):
|
||||
meta = _make_metadata(
|
||||
trained_words=[*self.KEPT, *self.SKIPPED, "", " ", None, 12]
|
||||
)
|
||||
tags, not_tags = lora_utils.trigger_word_tags(meta)
|
||||
self.assertEqual(tags, [entry.strip() for entry in self.KEPT])
|
||||
self.assertEqual(not_tags, len(self.SKIPPED))
|
||||
|
||||
def test_trigger_word_tags_without_trained_words(self):
|
||||
self.assertEqual(lora_utils.trigger_word_tags({}), ([], 0))
|
||||
|
||||
def test_trigger_words_still_hold_every_entry(self):
|
||||
meta = _make_metadata(trained_words=["neon", "a, b, c", "<lora:x:1>"])
|
||||
self.assertEqual(
|
||||
get_trigger_words_from_metadata(meta), ["neon", "a, b, c", "<lora:x:1>"]
|
||||
)
|
||||
|
||||
|
||||
class TestGetExamplePrompt(unittest.TestCase):
|
||||
"""Test get_example_prompt_from_metadata — extracts first usable prompt."""
|
||||
|
||||
@@ -1296,6 +1354,20 @@ class TestTriggerWordCache(unittest.TestCase):
|
||||
self.cache.get_trigger_words("my_lora"), ["trigger1", "trigger2"]
|
||||
)
|
||||
|
||||
def test_lists_and_sentences_stay_trigger_words(self):
|
||||
"""#618: the phrase rule only decides tags; the lookup keeps all."""
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
words = ["neon", "a, b, c", "<lora:x:1>"]
|
||||
meta = {
|
||||
"file_name": "lists.safetensors",
|
||||
"civitai": {"trainedWords": words},
|
||||
}
|
||||
(Path(tmpdir) / "lists.metadata.json").write_text(json.dumps(meta))
|
||||
(Path(tmpdir) / "lists.safetensors").write_bytes(b"m")
|
||||
with patch("py.lora_utils.default_lora_roots", return_value=[tmpdir]):
|
||||
self.cache.load(tmpdir)
|
||||
self.assertEqual(self.cache.get_trigger_words("lists"), words)
|
||||
|
||||
def test_case_insensitive_lookup(self):
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
meta = {
|
||||
|
||||
@@ -17,7 +17,9 @@
|
||||
* reviews the import (`POST /lora/import/preview`, read-only) and the shared review dialog shows what it replaces,
|
||||
* what saved pairs block, what it downloads and the backup box; Start runs the "LoRA reference import" Activity job.
|
||||
* #355: its first row, "LoraManager", names the settings source, storage mode and library the server read (the
|
||||
* settings file is the row's hover title); "Found" counts metadata files, LoRAs and LoRAs with local images. When
|
||||
* settings file is the row's hover title); "Found" counts metadata files, LoRAs and LoRAs with local images.
|
||||
* #618 (D210): "Trigger words", after Found and only when a count is above 0, says how many trained-words entries
|
||||
* become tags and how many are lists or sentences the import does not make tags. When
|
||||
* LoraManager's settings cannot be used, the plan has no token and the review says why and offers only Close.
|
||||
*/
|
||||
import { createButton } from '../shared/toolkit/core.js';
|
||||
@@ -198,6 +200,19 @@ export function closeNote(plan) {
|
||||
}
|
||||
|
||||
/** D107: the import review's rows from the server's plan. */
|
||||
/**
|
||||
* The "Trigger words" row (#618): how many trained-words entries become tags and how many are lists or sentences the
|
||||
* import does not make tags; null when neither is above 0.
|
||||
*/
|
||||
function triggerWordsText(plan) {
|
||||
const positive = value => (Number.isSafeInteger(value) && value > 0 ? value : 0);
|
||||
const tags = positive(plan.trigger_tags);
|
||||
const notTags = positive(plan.trigger_not_tags);
|
||||
if (!tags && !notTags) return null;
|
||||
const made = `${number(tags)} become tags`;
|
||||
return notTags ? `${made} · ${number(notTags)} not made tags (lists or sentences)` : made;
|
||||
}
|
||||
|
||||
export function importGrid(plan) {
|
||||
const downloads = Number.isSafeInteger(plan.planned_downloads) ? plan.planned_downloads : 0;
|
||||
const network = downloads
|
||||
@@ -208,11 +223,13 @@ export function importGrid(plan) {
|
||||
const readable = count(plan.with_metadata);
|
||||
const local = count(plan.with_local_media);
|
||||
const layout = layoutText(plan.layout);
|
||||
const triggers = triggerWordsText(plan);
|
||||
return [
|
||||
...(layout ? [[LAYOUT_TERM, layout]] : []),
|
||||
['Scope', plan.scope?.label || `${number(readable)} ${noun(readable, 'LoRA')}`],
|
||||
['Found', `${number(found)} metadata ${noun(found, 'file')} · ${number(readable)} ${noun(readable, 'LoRA')} · `
|
||||
+ `${number(local)} with local images`],
|
||||
...(triggers ? [['Trigger words', triggers]] : []),
|
||||
['Protected', protectedText(plan.protected)],
|
||||
['Network', network],
|
||||
['Backup', backupText(plan.backup)],
|
||||
|
||||
Reference in New Issue
Block a user