Skip to content

Commit

Permalink
improve en display
Browse files Browse the repository at this point in the history
  • Loading branch information
vladmandic committed Nov 5, 2023
1 parent b2328fc commit 2919774
Show file tree
Hide file tree
Showing 10 changed files with 51 additions and 48 deletions.
1 change: 1 addition & 0 deletions .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
"no-confusing-arrow":"off",
"no-console":"off",
"no-empty":"off",
"no-loop-func":"off",
"no-mixed-operators":"off",
"no-param-reassign":"off",
"no-plusplus":"off",
Expand Down
41 changes: 23 additions & 18 deletions javascript/extraNetworks.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const activePromptTextarea = {};
let sortVal = 0;

// helpers

Expand Down Expand Up @@ -92,22 +93,28 @@ async function filterExtraNetworksForTab(tabname, searchTerm) {
let found = 0;
let items = 0;
const t0 = performance.now();
const cards = Array.from(gradioApp().querySelectorAll(`#${tabname}_extra_tabs div.card`));
cards.forEach((elem) => {
items += 1;
if (searchTerm === '') {
elem.style.display = '';
} else {
let text = `${elem.querySelector('.name').textContent.toLowerCase()} ${elem.querySelector('.search_term').textContent}`;
text = text.toLowerCase().replace('models--', 'Diffusers').replace('\\', '/');
if (text.indexOf(searchTerm) === -1) {
elem.style.display = 'none';
} else {
const pagename = getENActivePage();
if (!pagename) return;
const allPages = Array.from(gradioApp().querySelectorAll('.extra-network-cards'));
const pages = allPages.filter((el) => el.id.includes(pagename.toLowerCase()));
for (const pg of pages) {
const cards = Array.from(pg.querySelectorAll('.card') || []);
cards.forEach((elem) => {
items += 1;
if (searchTerm === '') {
elem.style.display = '';
found += 1;
} else {
let text = elem.dataset.search.toLowerCase();
text = text.toLowerCase().replace('models--', 'Diffusers').replace('\\', '/');
if (text.indexOf(searchTerm) === -1) {
elem.style.display = 'none';
} else {
elem.style.display = '';
found += 1;
}
}
}
});
});
}
const t1 = performance.now();
if (found > 0) log(`filterExtraNetworks: text=${searchTerm} items=${items} match=${found} time=${Math.round(1000 * (t1 - t0)) / 1000000}`);
else log(`filterExtraNetworks: text=all items=${items} time=${Math.round(1000 * (t1 - t0)) / 1000000}`);
Expand Down Expand Up @@ -145,8 +152,6 @@ function tryToRemoveExtraNetworkFromPrompt(textarea, text) {
return false;
}

let sortVal = 0;

function sortExtraNetworks() {
const sortDesc = ['Name [A-Z]', 'Name [Z-A]', 'Date [Newest]', 'Date [Oldest]', 'Size [Largest]', 'Size [Smallest]'];
const pagename = getENActivePage();
Expand All @@ -160,8 +165,8 @@ function sortExtraNetworks() {
if (num === 0) return 'sort: no cards';
cards.sort((a, b) => { // eslint-disable-line no-loop-func
switch (sortVal) {
case 0: return a.dataset.name ? a.dataset.name.localeCompare(b.dataset.name) : 0;
case 1: return b.dataset.name ? b.dataset.name.localeCompare(a.dataset.name) : 0;
case 0: return a.dataset.name ? a.dataset.search.localeCompare(b.dataset.name) : 0;
case 1: return b.dataset.name ? b.dataset.search.localeCompare(a.dataset.name) : 0;
case 2: return a.dataset.mtime && !isNaN(a.dataset.mtime) ? parseFloat(b.dataset.mtime) - parseFloat(a.dataset.mtime) : 0;
case 3: return b.dataset.mtime && !isNaN(b.dataset.mtime) ? parseFloat(a.dataset.mtime) - parseFloat(b.dataset.mtime) : 0;
case 4: return a.dataset.size && !isNaN(a.dataset.size) ? parseFloat(b.dataset.size) - parseFloat(a.dataset.size) : 0;
Expand Down
2 changes: 1 addition & 1 deletion modules/images.py
Original file line number Diff line number Diff line change
Expand Up @@ -413,7 +413,7 @@ def sanitize(self, filename):
[part := part.replace(word, '_') for word in invalid_files] # pylint: disable=expression-not-assigned
newparts.append(part)
fn = Path(*newparts)
max_length = os.statvfs(__file__).f_namemax - 32 if hasattr(os, 'statvfs') else 230
max_length = max(230, os.statvfs(__file__).f_namemax - 32 if hasattr(os, 'statvfs') else 230)
fn = str(fn)[:max_length-max(4, len(ext))].rstrip(invalid_suffix) + ext
debug(f'Filename sanitize: input="{filename}" parts={parts} output="{fn}" ext={ext} max={max_length} len={len(fn)}')
return fn
Expand Down
11 changes: 5 additions & 6 deletions modules/ui_extra_networks.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,8 @@
extra_pages = shared.extra_networks
debug = shared.log.info if os.environ.get('SD_EN_DEBUG', None) is not None else lambda *args, **kwargs: None
card_full = '''
<div class='card' onclick={card_click} title='{name}' data-tab='{tabname}' data-page='{page}' data-name='{name}' data-filename='{filename}' data-tags='{tags}' data-mtime='{mtime}' data-size='{size}'>
<div class='card' onclick={card_click} title='{name}' data-tab='{tabname}' data-page='{page}' data-name='{name}' data-filename='{filename}' data-tags='{tags}' data-mtime='{mtime}' data-size='{size}' data-search='{search}'>
<div class='overlay'>
<span style="display:none" class='search_term'>{search_term}</span>
<div class='tags'></div>
<div class='name'>{title}</div>
</div>
Expand All @@ -39,11 +38,10 @@
</div>
'''
card_list = '''
<div class='card card-list' onclick={card_click} title='{name}' data-tab='{tabname}' data-page='{page}' data-name='{name}' data-filename='{filename}' data-tags='{tags}' data-mtime='{mtime}' data-size='{size}'>
<div class='card card-list' onclick={card_click} title='{name}' data-tab='{tabname}' data-page='{page}' data-name='{name}' data-filename='{filename}' data-tags='{tags}' data-mtime='{mtime}' data-size='{size}' data-search='{search}'>
<span class='details' title="Get details" onclick="showCardDetails(event)">&#x1f6c8;</span>&nbsp;
<div class='name'>{title}</div>&nbsp;
<div class='tags tags-list'></div>
<span style="display:none" class='search_term'>{search_term}</span>
</div>
'''

Expand Down Expand Up @@ -258,6 +256,7 @@ def create_page(self, tabname, skip = False):
self.create_items(tabname)
self.create_xyz_grid()
htmls = []
self.items.sort(key=lambda x: x["mtime"], reverse=True)
for item in self.items:
htmls.append(self.create_html(item, tabname))
self.html += ''.join(htmls)
Expand All @@ -283,15 +282,15 @@ def create_html(self, item, tabname):
"tabname": tabname,
"page": self.name,
"name": item["name"],
"title": item["name"].replace('_', ' '),
"title": os.path.basename(item["name"].replace('_', ' ')),
"filename": item["filename"],
"tags": '|'.join([item.get("tags")] if isinstance(item.get("tags", {}), str) else list(item.get("tags", {}).keys())),
"preview": html.escape(item.get("preview", self.link_preview('html/card-no-preview.png'))),
"width": shared.opts.extra_networks_card_size,
"height": shared.opts.extra_networks_card_size if shared.opts.extra_networks_card_square else 'auto',
"fit": shared.opts.extra_networks_card_fit,
"prompt": item.get("prompt", None),
"search_term": item.get("search_term", ""),
"search": item.get("search_term", ""),
"description": item.get("description") or "",
"card_click": item.get("onclick", '"' + html.escape(f'return cardClicked({item.get("prompt", None)}, {"true" if self.allow_negative_prompt else "false"})') + '"'),
"mtime": item.get("mtime", 0),
Expand Down
9 changes: 4 additions & 5 deletions modules/ui_extra_networks_checkpoints.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,23 +16,22 @@ def list_items(self):
checkpoints = sd_models.checkpoints_list.copy()
for name, checkpoint in checkpoints.items():
try:
fn = os.path.splitext(checkpoint.filename)[0]
record = {
"type": 'Model',
"name": checkpoint.name,
"title": checkpoint.title,
"filename": checkpoint.filename,
"hash": checkpoint.shorthash,
"search_term": self.search_terms_from_path(checkpoint.title),
"preview": self.find_preview(fn),
"local_preview": f"{fn}.{shared.opts.samples_format}",
"preview": self.find_preview(checkpoint.filename),
"local_preview": f"{os.path.splitext(checkpoint.filename)[0]}.{shared.opts.samples_format}",
"metadata": checkpoint.metadata,
"onclick": '"' + html.escape(f"""return selectCheckpoint({json.dumps(name)})""") + '"',
"mtime": os.path.getmtime(checkpoint.filename),
"size": os.path.getsize(checkpoint.filename),
}
record["info"] = self.find_info(fn)
record["description"] = self.find_description(fn, record["info"])
record["info"] = self.find_info(checkpoint.filename)
record["description"] = self.find_description(checkpoint.filename, record["info"])
yield record
except Exception as e:
shared.log.debug(f"Extra networks error: type=model file={name} {e}")
Expand Down
14 changes: 7 additions & 7 deletions modules/ui_extra_networks_hypernets.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,17 @@ def list_items(self):
for name, path in shared.hypernetworks.items():
try:
fn = os.path.splitext(path)[0]
name = os.path.relpath(fn, shared.opts.hypernetwork_dir)
name = os.path.relpath(os.path.splitext(path)[0], shared.opts.hypernetwork_dir)
yield {
"type": 'Hypernetwork',
"name": os.path.relpath(fn, shared.opts.hypernetwork_dir),
"name": name,
"filename": path,
"preview": self.find_preview(fn),
"description": self.find_description(fn),
"info": self.find_info(fn),
"preview": self.find_preview(path),
"description": self.find_description(path),
"info": self.find_info(path),
"search_term": self.search_terms_from_path(name),
"prompt": json.dumps(f"<hypernet:{name}:{shared.opts.extra_networks_default_multiplier}>"),
"local_preview": f"{fn}.{shared.opts.samples_format}",
"prompt": json.dumps(f"<hypernet:{os.path.basename(name)}:{shared.opts.extra_networks_default_multiplier}>"),
"local_preview": f"{os.path.splitext(path)[0]}.{shared.opts.samples_format}",
"mtime": os.path.getmtime(path),
"size": os.path.getsize(path),
}
Expand Down
2 changes: 1 addition & 1 deletion modules/ui_extra_networks_textual_inversion.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ def list_folder(folder):
"type": 'Embedding',
"name": name,
"filename": embedding.filename,
"preview": self.find_preview(path),
"preview": self.find_preview(embedding.filename),
"search_term": self.search_terms_from_path(name),
"prompt": json.dumps(f" {os.path.splitext(embedding.name)[0]}"),
"local_preview": f"{path}.{shared.opts.samples_format}",
Expand Down
15 changes: 7 additions & 8 deletions modules/ui_extra_networks_vae.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,23 +14,22 @@ def refresh(self):
def list_items(self):
for name, filename in sd_vae.vae_dict.items():
try:
fn = os.path.splitext(filename)[0]
record = {
"type": 'VAE',
"name": name,
"title": name,
"filename": fn,
"hash": hashes.sha256_from_cache(filename, f"vae/{fn}"),
"search_term": self.search_terms_from_path(fn),
"preview": self.find_preview(fn),
"local_preview": f"{fn}.{shared.opts.samples_format}",
"filename": filename,
"hash": hashes.sha256_from_cache(filename, f"vae/{filename}"),
"search_term": self.search_terms_from_path(filename),
"preview": self.find_preview(filename),
"local_preview": f"{os.path.splitext(filename)[0]}.{shared.opts.samples_format}",
"metadata": {},
"onclick": '"' + html.escape(f"""return selectVAE({json.dumps(name)})""") + '"',
"mtime": os.path.getmtime(filename),
"size": os.path.getsize(filename),
}
record["info"] = self.find_info(fn)
record["description"] = self.find_description(fn, record["info"])
record["info"] = self.find_info(filename)
record["description"] = self.find_description(filename, record["info"])
yield record
except Exception as e:
shared.log.debug(f"Extra networks error: type=vae file={filename} {e}")
Expand Down

0 comments on commit 2919774

Please sign in to comment.