From 8a7c07a2140c98bceca858087525d77fd0352fda Mon Sep 17 00:00:00 2001 From: yfszzx Date: Mon, 10 Oct 2022 15:39:39 +0800 Subject: [PATCH 01/11] show image history --- javascript/images_history.js | 66 ++++++++++++++++++ javascript/jquery-3.6.0.min.js | 2 + modules/images_history.py | 90 ++++++++++++++++++++++++ modules/ui.py | 11 ++- repositorieslatent-diffusion | 1 + testui.py | 124 +++++++++++++++++++++++++++++++++ 6 files changed, 292 insertions(+), 2 deletions(-) create mode 100644 javascript/images_history.js create mode 100644 javascript/jquery-3.6.0.min.js create mode 100644 modules/images_history.py create mode 160000 repositorieslatent-diffusion create mode 100644 testui.py diff --git a/javascript/images_history.js b/javascript/images_history.js new file mode 100644 index 000000000..f30b7eff3 --- /dev/null +++ b/javascript/images_history.js @@ -0,0 +1,66 @@ +function init_images_history(){ + if (gradioApp().getElementById('txt2img_images_history_first_page') == null) { + setTimeout(init_images_history, 1000) + } else { + tab_list = ["txt2img", "img2img"] + for (i in tab_list){ + tab = tab_list[i] + gradioApp().getElementById(tab + "_images_history_first_page").click() + $(gradioApp().getElementById(tab + '_images_history')).addClass("images_history_gallery") + item = $(gradioApp().getElementById(tab + '_images_history_set_index')) + item.addClass("images_history_set_index") + item.hide() + } + } + +} +setTimeout(init_images_history, 1000) +onUiUpdate(function(){ + fullImg_preview = gradioApp().querySelectorAll('#txt2img_images_history img.w-full') + if(fullImg_preview.length > 0){ + fullImg_preview.forEach(set_history_index_from_img); + } + fullImg_preview = gradioApp().querySelectorAll('#img2img_images_history img.w-full') + if(fullImg_preview.length > 0){ + fullImg_preview.forEach(set_history_index_from_img); + } +}) + +function set_history_gallery_index(item){ + buttons = item.find(".gallery-item") + // alert(item.attr("id") + " " + buttons.length) + index = -1 + i = 0 + buttons.each(function(){ + if($(this).hasClass("!ring-2")){ index = i } + i += 1 + }) + if (index == -1){ + setTimeout(set_history_gallery_index, 10, item) + } else { + item = item.find(".images_history_set_index").first() + item.attr("img_index", index) + item.click() + } +} +function set_history_index_from_img(e){ + if(e && e.parentElement.tagName == 'BUTTON'){ + bnt = $(e).parent() + if (bnt.hasClass("transform")){ + bnt.off("click").on("click",function(){ + set_history_gallery_index($(this).parents(".images_history_gallery").first()) + }) + } else { + bnt.off("mousedown").on("mousedown", function(){ + set_history_gallery_index($(this).parents(".images_history_gallery").first()) + }) + + } + } +} +function images_history_get_current_img(is_image2image){ + head = is_image2image?"img2img":"txt2img" + s = $(gradioApp().getElementById(head + '_images_history_set_index')).attr("img_index") + return s +} + diff --git a/javascript/jquery-3.6.0.min.js b/javascript/jquery-3.6.0.min.js new file mode 100644 index 000000000..c4c6022f2 --- /dev/null +++ b/javascript/jquery-3.6.0.min.js @@ -0,0 +1,2 @@ +/*! jQuery v3.6.0 | (c) OpenJS Foundation and other contributors | jquery.org/license */ +!function(e,t){"use strict";"object"==typeof module&&"object"==typeof module.exports?module.exports=e.document?t(e,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return t(e)}:t(e)}("undefined"!=typeof window?window:this,function(C,e){"use strict";var t=[],r=Object.getPrototypeOf,s=t.slice,g=t.flat?function(e){return t.flat.call(e)}:function(e){return t.concat.apply([],e)},u=t.push,i=t.indexOf,n={},o=n.toString,v=n.hasOwnProperty,a=v.toString,l=a.call(Object),y={},m=function(e){return"function"==typeof e&&"number"!=typeof e.nodeType&&"function"!=typeof e.item},x=function(e){return null!=e&&e===e.window},E=C.document,c={type:!0,src:!0,nonce:!0,noModule:!0};function b(e,t,n){var r,i,o=(n=n||E).createElement("script");if(o.text=e,t)for(r in c)(i=t[r]||t.getAttribute&&t.getAttribute(r))&&o.setAttribute(r,i);n.head.appendChild(o).parentNode.removeChild(o)}function w(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?n[o.call(e)]||"object":typeof e}var f="3.6.0",S=function(e,t){return new S.fn.init(e,t)};function p(e){var t=!!e&&"length"in e&&e.length,n=w(e);return!m(e)&&!x(e)&&("array"===n||0===t||"number"==typeof t&&0+~]|"+M+")"+M+"*"),U=new RegExp(M+"|>"),X=new RegExp(F),V=new RegExp("^"+I+"$"),G={ID:new RegExp("^#("+I+")"),CLASS:new RegExp("^\\.("+I+")"),TAG:new RegExp("^("+I+"|[*])"),ATTR:new RegExp("^"+W),PSEUDO:new RegExp("^"+F),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+R+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Y=/HTML$/i,Q=/^(?:input|select|textarea|button)$/i,J=/^h\d$/i,K=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ee=/[+~]/,te=new RegExp("\\\\[\\da-fA-F]{1,6}"+M+"?|\\\\([^\\r\\n\\f])","g"),ne=function(e,t){var n="0x"+e.slice(1)-65536;return t||(n<0?String.fromCharCode(n+65536):String.fromCharCode(n>>10|55296,1023&n|56320))},re=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,ie=function(e,t){return t?"\0"===e?"\ufffd":e.slice(0,-1)+"\\"+e.charCodeAt(e.length-1).toString(16)+" ":"\\"+e},oe=function(){T()},ae=be(function(e){return!0===e.disabled&&"fieldset"===e.nodeName.toLowerCase()},{dir:"parentNode",next:"legend"});try{H.apply(t=O.call(p.childNodes),p.childNodes),t[p.childNodes.length].nodeType}catch(e){H={apply:t.length?function(e,t){L.apply(e,O.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function se(t,e,n,r){var i,o,a,s,u,l,c,f=e&&e.ownerDocument,p=e?e.nodeType:9;if(n=n||[],"string"!=typeof t||!t||1!==p&&9!==p&&11!==p)return n;if(!r&&(T(e),e=e||C,E)){if(11!==p&&(u=Z.exec(t)))if(i=u[1]){if(9===p){if(!(a=e.getElementById(i)))return n;if(a.id===i)return n.push(a),n}else if(f&&(a=f.getElementById(i))&&y(e,a)&&a.id===i)return n.push(a),n}else{if(u[2])return H.apply(n,e.getElementsByTagName(t)),n;if((i=u[3])&&d.getElementsByClassName&&e.getElementsByClassName)return H.apply(n,e.getElementsByClassName(i)),n}if(d.qsa&&!N[t+" "]&&(!v||!v.test(t))&&(1!==p||"object"!==e.nodeName.toLowerCase())){if(c=t,f=e,1===p&&(U.test(t)||z.test(t))){(f=ee.test(t)&&ye(e.parentNode)||e)===e&&d.scope||((s=e.getAttribute("id"))?s=s.replace(re,ie):e.setAttribute("id",s=S)),o=(l=h(t)).length;while(o--)l[o]=(s?"#"+s:":scope")+" "+xe(l[o]);c=l.join(",")}try{return H.apply(n,f.querySelectorAll(c)),n}catch(e){N(t,!0)}finally{s===S&&e.removeAttribute("id")}}}return g(t.replace($,"$1"),e,n,r)}function ue(){var r=[];return function e(t,n){return r.push(t+" ")>b.cacheLength&&delete e[r.shift()],e[t+" "]=n}}function le(e){return e[S]=!0,e}function ce(e){var t=C.createElement("fieldset");try{return!!e(t)}catch(e){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function fe(e,t){var n=e.split("|"),r=n.length;while(r--)b.attrHandle[n[r]]=t}function pe(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&e.sourceIndex-t.sourceIndex;if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function de(t){return function(e){return"input"===e.nodeName.toLowerCase()&&e.type===t}}function he(n){return function(e){var t=e.nodeName.toLowerCase();return("input"===t||"button"===t)&&e.type===n}}function ge(t){return function(e){return"form"in e?e.parentNode&&!1===e.disabled?"label"in e?"label"in e.parentNode?e.parentNode.disabled===t:e.disabled===t:e.isDisabled===t||e.isDisabled!==!t&&ae(e)===t:e.disabled===t:"label"in e&&e.disabled===t}}function ve(a){return le(function(o){return o=+o,le(function(e,t){var n,r=a([],e.length,o),i=r.length;while(i--)e[n=r[i]]&&(e[n]=!(t[n]=e[n]))})})}function ye(e){return e&&"undefined"!=typeof e.getElementsByTagName&&e}for(e in d=se.support={},i=se.isXML=function(e){var t=e&&e.namespaceURI,n=e&&(e.ownerDocument||e).documentElement;return!Y.test(t||n&&n.nodeName||"HTML")},T=se.setDocument=function(e){var t,n,r=e?e.ownerDocument||e:p;return r!=C&&9===r.nodeType&&r.documentElement&&(a=(C=r).documentElement,E=!i(C),p!=C&&(n=C.defaultView)&&n.top!==n&&(n.addEventListener?n.addEventListener("unload",oe,!1):n.attachEvent&&n.attachEvent("onunload",oe)),d.scope=ce(function(e){return a.appendChild(e).appendChild(C.createElement("div")),"undefined"!=typeof e.querySelectorAll&&!e.querySelectorAll(":scope fieldset div").length}),d.attributes=ce(function(e){return e.className="i",!e.getAttribute("className")}),d.getElementsByTagName=ce(function(e){return e.appendChild(C.createComment("")),!e.getElementsByTagName("*").length}),d.getElementsByClassName=K.test(C.getElementsByClassName),d.getById=ce(function(e){return a.appendChild(e).id=S,!C.getElementsByName||!C.getElementsByName(S).length}),d.getById?(b.filter.ID=function(e){var t=e.replace(te,ne);return function(e){return e.getAttribute("id")===t}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&E){var n=t.getElementById(e);return n?[n]:[]}}):(b.filter.ID=function(e){var n=e.replace(te,ne);return function(e){var t="undefined"!=typeof e.getAttributeNode&&e.getAttributeNode("id");return t&&t.value===n}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&E){var n,r,i,o=t.getElementById(e);if(o){if((n=o.getAttributeNode("id"))&&n.value===e)return[o];i=t.getElementsByName(e),r=0;while(o=i[r++])if((n=o.getAttributeNode("id"))&&n.value===e)return[o]}return[]}}),b.find.TAG=d.getElementsByTagName?function(e,t){return"undefined"!=typeof t.getElementsByTagName?t.getElementsByTagName(e):d.qsa?t.querySelectorAll(e):void 0}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},b.find.CLASS=d.getElementsByClassName&&function(e,t){if("undefined"!=typeof t.getElementsByClassName&&E)return t.getElementsByClassName(e)},s=[],v=[],(d.qsa=K.test(C.querySelectorAll))&&(ce(function(e){var t;a.appendChild(e).innerHTML="",e.querySelectorAll("[msallowcapture^='']").length&&v.push("[*^$]="+M+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||v.push("\\["+M+"*(?:value|"+R+")"),e.querySelectorAll("[id~="+S+"-]").length||v.push("~="),(t=C.createElement("input")).setAttribute("name",""),e.appendChild(t),e.querySelectorAll("[name='']").length||v.push("\\["+M+"*name"+M+"*="+M+"*(?:''|\"\")"),e.querySelectorAll(":checked").length||v.push(":checked"),e.querySelectorAll("a#"+S+"+*").length||v.push(".#.+[+~]"),e.querySelectorAll("\\\f"),v.push("[\\r\\n\\f]")}),ce(function(e){e.innerHTML="";var t=C.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&v.push("name"+M+"*[*^$|!~]?="),2!==e.querySelectorAll(":enabled").length&&v.push(":enabled",":disabled"),a.appendChild(e).disabled=!0,2!==e.querySelectorAll(":disabled").length&&v.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),v.push(",.*:")})),(d.matchesSelector=K.test(c=a.matches||a.webkitMatchesSelector||a.mozMatchesSelector||a.oMatchesSelector||a.msMatchesSelector))&&ce(function(e){d.disconnectedMatch=c.call(e,"*"),c.call(e,"[s!='']:x"),s.push("!=",F)}),v=v.length&&new RegExp(v.join("|")),s=s.length&&new RegExp(s.join("|")),t=K.test(a.compareDocumentPosition),y=t||K.test(a.contains)?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},j=t?function(e,t){if(e===t)return l=!0,0;var n=!e.compareDocumentPosition-!t.compareDocumentPosition;return n||(1&(n=(e.ownerDocument||e)==(t.ownerDocument||t)?e.compareDocumentPosition(t):1)||!d.sortDetached&&t.compareDocumentPosition(e)===n?e==C||e.ownerDocument==p&&y(p,e)?-1:t==C||t.ownerDocument==p&&y(p,t)?1:u?P(u,e)-P(u,t):0:4&n?-1:1)}:function(e,t){if(e===t)return l=!0,0;var n,r=0,i=e.parentNode,o=t.parentNode,a=[e],s=[t];if(!i||!o)return e==C?-1:t==C?1:i?-1:o?1:u?P(u,e)-P(u,t):0;if(i===o)return pe(e,t);n=e;while(n=n.parentNode)a.unshift(n);n=t;while(n=n.parentNode)s.unshift(n);while(a[r]===s[r])r++;return r?pe(a[r],s[r]):a[r]==p?-1:s[r]==p?1:0}),C},se.matches=function(e,t){return se(e,null,null,t)},se.matchesSelector=function(e,t){if(T(e),d.matchesSelector&&E&&!N[t+" "]&&(!s||!s.test(t))&&(!v||!v.test(t)))try{var n=c.call(e,t);if(n||d.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(e){N(t,!0)}return 0":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(te,ne),e[3]=(e[3]||e[4]||e[5]||"").replace(te,ne),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||se.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&se.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return G.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&X.test(n)&&(t=h(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(te,ne).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=m[e+" "];return t||(t=new RegExp("(^|"+M+")"+e+"("+M+"|$)"))&&m(e,function(e){return t.test("string"==typeof e.className&&e.className||"undefined"!=typeof e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(n,r,i){return function(e){var t=se.attr(e,n);return null==t?"!="===r:!r||(t+="","="===r?t===i:"!="===r?t!==i:"^="===r?i&&0===t.indexOf(i):"*="===r?i&&-1:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i;function j(e,n,r){return m(n)?S.grep(e,function(e,t){return!!n.call(e,t,e)!==r}):n.nodeType?S.grep(e,function(e){return e===n!==r}):"string"!=typeof n?S.grep(e,function(e){return-1)[^>]*|#([\w-]+))$/;(S.fn.init=function(e,t,n){var r,i;if(!e)return this;if(n=n||D,"string"==typeof e){if(!(r="<"===e[0]&&">"===e[e.length-1]&&3<=e.length?[null,e,null]:q.exec(e))||!r[1]&&t)return!t||t.jquery?(t||n).find(e):this.constructor(t).find(e);if(r[1]){if(t=t instanceof S?t[0]:t,S.merge(this,S.parseHTML(r[1],t&&t.nodeType?t.ownerDocument||t:E,!0)),N.test(r[1])&&S.isPlainObject(t))for(r in t)m(this[r])?this[r](t[r]):this.attr(r,t[r]);return this}return(i=E.getElementById(r[2]))&&(this[0]=i,this.length=1),this}return e.nodeType?(this[0]=e,this.length=1,this):m(e)?void 0!==n.ready?n.ready(e):e(S):S.makeArray(e,this)}).prototype=S.fn,D=S(E);var L=/^(?:parents|prev(?:Until|All))/,H={children:!0,contents:!0,next:!0,prev:!0};function O(e,t){while((e=e[t])&&1!==e.nodeType);return e}S.fn.extend({has:function(e){var t=S(e,this),n=t.length;return this.filter(function(){for(var e=0;e\x20\t\r\n\f]*)/i,he=/^$|^module$|\/(?:java|ecma)script/i;ce=E.createDocumentFragment().appendChild(E.createElement("div")),(fe=E.createElement("input")).setAttribute("type","radio"),fe.setAttribute("checked","checked"),fe.setAttribute("name","t"),ce.appendChild(fe),y.checkClone=ce.cloneNode(!0).cloneNode(!0).lastChild.checked,ce.innerHTML="",y.noCloneChecked=!!ce.cloneNode(!0).lastChild.defaultValue,ce.innerHTML="",y.option=!!ce.lastChild;var ge={thead:[1,"","
"],col:[2,"","
"],tr:[2,"","
"],td:[3,"","
"],_default:[0,"",""]};function ve(e,t){var n;return n="undefined"!=typeof e.getElementsByTagName?e.getElementsByTagName(t||"*"):"undefined"!=typeof e.querySelectorAll?e.querySelectorAll(t||"*"):[],void 0===t||t&&A(e,t)?S.merge([e],n):n}function ye(e,t){for(var n=0,r=e.length;n",""]);var me=/<|&#?\w+;/;function xe(e,t,n,r,i){for(var o,a,s,u,l,c,f=t.createDocumentFragment(),p=[],d=0,h=e.length;d\s*$/g;function je(e,t){return A(e,"table")&&A(11!==t.nodeType?t:t.firstChild,"tr")&&S(e).children("tbody")[0]||e}function De(e){return e.type=(null!==e.getAttribute("type"))+"/"+e.type,e}function qe(e){return"true/"===(e.type||"").slice(0,5)?e.type=e.type.slice(5):e.removeAttribute("type"),e}function Le(e,t){var n,r,i,o,a,s;if(1===t.nodeType){if(Y.hasData(e)&&(s=Y.get(e).events))for(i in Y.remove(t,"handle events"),s)for(n=0,r=s[i].length;n").attr(n.scriptAttrs||{}).prop({charset:n.scriptCharset,src:n.url}).on("load error",i=function(e){r.remove(),i=null,e&&t("error"===e.type?404:200,e.type)}),E.head.appendChild(r[0])},abort:function(){i&&i()}}});var _t,zt=[],Ut=/(=)\?(?=&|$)|\?\?/;S.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=zt.pop()||S.expando+"_"+wt.guid++;return this[e]=!0,e}}),S.ajaxPrefilter("json jsonp",function(e,t,n){var r,i,o,a=!1!==e.jsonp&&(Ut.test(e.url)?"url":"string"==typeof e.data&&0===(e.contentType||"").indexOf("application/x-www-form-urlencoded")&&Ut.test(e.data)&&"data");if(a||"jsonp"===e.dataTypes[0])return r=e.jsonpCallback=m(e.jsonpCallback)?e.jsonpCallback():e.jsonpCallback,a?e[a]=e[a].replace(Ut,"$1"+r):!1!==e.jsonp&&(e.url+=(Tt.test(e.url)?"&":"?")+e.jsonp+"="+r),e.converters["script json"]=function(){return o||S.error(r+" was not called"),o[0]},e.dataTypes[0]="json",i=C[r],C[r]=function(){o=arguments},n.always(function(){void 0===i?S(C).removeProp(r):C[r]=i,e[r]&&(e.jsonpCallback=t.jsonpCallback,zt.push(r)),o&&m(i)&&i(o[0]),o=i=void 0}),"script"}),y.createHTMLDocument=((_t=E.implementation.createHTMLDocument("").body).innerHTML="
",2===_t.childNodes.length),S.parseHTML=function(e,t,n){return"string"!=typeof e?[]:("boolean"==typeof t&&(n=t,t=!1),t||(y.createHTMLDocument?((r=(t=E.implementation.createHTMLDocument("")).createElement("base")).href=E.location.href,t.head.appendChild(r)):t=E),o=!n&&[],(i=N.exec(e))?[t.createElement(i[1])]:(i=xe([e],t,o),o&&o.length&&S(o).remove(),S.merge([],i.childNodes)));var r,i,o},S.fn.load=function(e,t,n){var r,i,o,a=this,s=e.indexOf(" ");return-1").append(S.parseHTML(e)).find(r):e)}).always(n&&function(e,t){a.each(function(){n.apply(this,o||[e.responseText,t,e])})}),this},S.expr.pseudos.animated=function(t){return S.grep(S.timers,function(e){return t===e.elem}).length},S.offset={setOffset:function(e,t,n){var r,i,o,a,s,u,l=S.css(e,"position"),c=S(e),f={};"static"===l&&(e.style.position="relative"),s=c.offset(),o=S.css(e,"top"),u=S.css(e,"left"),("absolute"===l||"fixed"===l)&&-1<(o+u).indexOf("auto")?(a=(r=c.position()).top,i=r.left):(a=parseFloat(o)||0,i=parseFloat(u)||0),m(t)&&(t=t.call(e,n,S.extend({},s))),null!=t.top&&(f.top=t.top-s.top+a),null!=t.left&&(f.left=t.left-s.left+i),"using"in t?t.using.call(e,f):c.css(f)}},S.fn.extend({offset:function(t){if(arguments.length)return void 0===t?this:this.each(function(e){S.offset.setOffset(this,t,e)});var e,n,r=this[0];return r?r.getClientRects().length?(e=r.getBoundingClientRect(),n=r.ownerDocument.defaultView,{top:e.top+n.pageYOffset,left:e.left+n.pageXOffset}):{top:0,left:0}:void 0},position:function(){if(this[0]){var e,t,n,r=this[0],i={top:0,left:0};if("fixed"===S.css(r,"position"))t=r.getBoundingClientRect();else{t=this.offset(),n=r.ownerDocument,e=r.offsetParent||n.documentElement;while(e&&(e===n.body||e===n.documentElement)&&"static"===S.css(e,"position"))e=e.parentNode;e&&e!==r&&1===e.nodeType&&((i=S(e).offset()).top+=S.css(e,"borderTopWidth",!0),i.left+=S.css(e,"borderLeftWidth",!0))}return{top:t.top-i.top-S.css(r,"marginTop",!0),left:t.left-i.left-S.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent;while(e&&"static"===S.css(e,"position"))e=e.offsetParent;return e||re})}}),S.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(t,i){var o="pageYOffset"===i;S.fn[t]=function(e){return $(this,function(e,t,n){var r;if(x(e)?r=e:9===e.nodeType&&(r=e.defaultView),void 0===n)return r?r[i]:e[t];r?r.scrollTo(o?r.pageXOffset:n,o?n:r.pageYOffset):e[t]=n},t,e,arguments.length)}}),S.each(["top","left"],function(e,n){S.cssHooks[n]=Fe(y.pixelPosition,function(e,t){if(t)return t=We(e,n),Pe.test(t)?S(e).position()[n]+"px":t})}),S.each({Height:"height",Width:"width"},function(a,s){S.each({padding:"inner"+a,content:s,"":"outer"+a},function(r,o){S.fn[o]=function(e,t){var n=arguments.length&&(r||"boolean"!=typeof e),i=r||(!0===e||!0===t?"margin":"border");return $(this,function(e,t,n){var r;return x(e)?0===o.indexOf("outer")?e["inner"+a]:e.document.documentElement["client"+a]:9===e.nodeType?(r=e.documentElement,Math.max(e.body["scroll"+a],r["scroll"+a],e.body["offset"+a],r["offset"+a],r["client"+a])):void 0===n?S.css(e,t,i):S.style(e,t,n,i)},s,n?e:void 0,n)}})}),S.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){S.fn[t]=function(e){return this.on(t,e)}}),S.fn.extend({bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)},hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)}}),S.each("blur focus focusin focusout resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu".split(" "),function(e,n){S.fn[n]=function(e,t){return 0 max_page_index else page_index + idx_frm = (page_index - 1) * num + file_list = file_list[idx_frm:idx_frm + num] + print(f"Loading history page {page_index}") + return [os.path.join(dir_name, file) for file in file_list], page_index, file_list +def first_page_click(is_img2img, dir_name): + return get_recent_images(is_img2img, dir_name, 1, 0) +def end_page_click(is_img2img, dir_name): + return get_recent_images(is_img2img, dir_name, -1, 0) +def prev_page_click(is_img2img, dir_name, page_index): + return get_recent_images(is_img2img, dir_name, page_index, -1) +def next_page_click(is_img2img, dir_name, page_index): + return get_recent_images(is_img2img, dir_name, page_index, 1) +def page_index_change(is_img2img, dir_name, page_index): + return get_recent_images(is_img2img, dir_name, page_index, 0) +def show_image_info(num, filenames): + return filenames[int(num)] +def delete_image(is_img2img, dir_name, name, page_index, filenames): + path = os.path.join(dir_name, name) + if os.path.exists(path): + print(f"Delete file {path}") + os.remove(path) + i = 0 + for f in filenames: + if f == name: + break + i += 1 + images, page_index, file_list = get_recent_images(is_img2img, dir_name, page_index, 0) + current_file = file_list[i] if i < len(file_list) else None + return images, page_index, file_list, current_file + + +def show_images_history(gr, opts, is_img2img): + def id_name(is_img2img, name): + return ("img2img" if is_img2img else "txt2img") + "_" + name + with gr.Row(): + if is_img2img: + dir_name = opts.outdir_img2img_samples + else: + dir_name = opts.outdir_txt2img_samples + first_page = gr.Button('First Page', elem_id=id_name(is_img2img,"images_history_first_page")) + prev_page = gr.Button('Prev Page') + page_index = gr.Number(value=1) + next_page = gr.Button('Next Page') + end_page = gr.Button('End Page') + with gr.Row(): + delete = gr.Button('Delete') + Send = gr.Button('Send') + with gr.Row(): + with gr.Column(elem_id=id_name(is_img2img,"images_history")): + history_gallery = gr.Gallery(label="Images history").style(grid=6) + img_file_name = gr.Textbox() + img_file_info = gr.Textbox(dir_name) + img_path = gr.Textbox(dir_name, visible=False) + set_index = gr.Button('set_index', elem_id=id_name(is_img2img,"images_history_set_index")) + is_img2img_flag = gr.Checkbox(is_img2img, visible=False) + filenames = gr.State() + first_page.click(first_page_click, inputs=[is_img2img_flag, img_path], outputs=[history_gallery, page_index, filenames]) + next_page.click(next_page_click, inputs=[is_img2img_flag, img_path, page_index], outputs=[history_gallery, page_index, filenames]) + prev_page.click(prev_page_click, inputs=[is_img2img_flag, img_path, page_index], outputs=[history_gallery, page_index, filenames]) + end_page.click(end_page_click, inputs=[is_img2img_flag, img_path], outputs=[history_gallery, page_index, filenames]) + page_index.submit(page_index_change, inputs=[is_img2img_flag, img_path, page_index], outputs=[history_gallery, page_index, filenames]) + set_index.click(show_image_info, _js="images_history_get_current_img",inputs=[is_img2img_flag, filenames], outputs=img_file_name) + delete.click(delete_image, inputs=[is_img2img_flag, img_path, img_file_name, page_index, filenames], outputs=[history_gallery, page_index, filenames,img_file_name]) + #page_index.change(page_index_change, inputs=[is_img2img_flag, img_path, page_index], outputs=[history_gallery, page_index]) + +def create_history_tabs(gr, opts): + with gr.Blocks(analytics_enabled=False) as images_history: + with gr.Tabs() as tabs: + with gr.Tab("txt2img history", id="images_history_txt2img"): + with gr.Blocks(analytics_enabled=False) as images_history_txt2img: + show_images_history(gr, opts, is_img2img=False) + with gr.Tab("img2img history", id="images_history_img2img"): + with gr.Blocks(analytics_enabled=False) as images_history_img2img: + show_images_history(gr, opts, is_img2img=True) + return images_history diff --git a/modules/ui.py b/modules/ui.py index 4f18126fb..8762fcf54 100644 --- a/modules/ui.py +++ b/modules/ui.py @@ -37,6 +37,7 @@ import modules.generation_parameters_copypaste from modules import prompt_parser from modules.images import save_image import modules.textual_inversion.ui +import modules.images_history as img_his # this is a fix for Windows users. Without it, javascript files will be served with text/html content-type and the bowser will not show any UI mimetypes.init() @@ -499,7 +500,6 @@ def create_ui(wrap_gradio_gpu_call): custom_inputs = modules.scripts.scripts_txt2img.setup_ui(is_img2img=False) with gr.Column(variant='panel'): - with gr.Group(): txt2img_preview = gr.Image(elem_id='txt2img_preview', visible=False) txt2img_gallery = gr.Gallery(label='Output', show_label=False, elem_id='txt2img_gallery').style(grid=4) @@ -516,6 +516,7 @@ def create_ui(wrap_gradio_gpu_call): with gr.Group(): html_info = gr.HTML() generation_info = gr.Textbox(visible=False) + connect_reuse_seed(seed, reuse_seed, generation_info, dummy_component, is_subseed=False) connect_reuse_seed(subseed, reuse_subseed, generation_info, dummy_component, is_subseed=True) @@ -607,6 +608,7 @@ def create_ui(wrap_gradio_gpu_call): ] modules.generation_parameters_copypaste.connect_paste(paste, txt2img_paste_fields, txt2img_prompt) token_button.click(fn=update_token_counter, inputs=[txt2img_prompt, steps], outputs=[token_counter]) + with gr.Blocks(analytics_enabled=False) as img2img_interface: img2img_prompt, roll, img2img_prompt_style, img2img_negative_prompt, img2img_prompt_style2, submit, img2img_interrogate, img2img_prompt_style_apply, img2img_save_style, paste, token_counter, token_button = create_toprow(is_img2img=True) @@ -696,6 +698,7 @@ def create_ui(wrap_gradio_gpu_call): with gr.Group(): html_info = gr.HTML() generation_info = gr.Textbox(visible=False) + connect_reuse_seed(seed, reuse_seed, generation_info, dummy_component, is_subseed=False) connect_reuse_seed(subseed, reuse_subseed, generation_info, dummy_component, is_subseed=True) @@ -1126,8 +1129,10 @@ def create_ui(wrap_gradio_gpu_call): opts.save(shared.config_filename) - return f'{changed} settings changed.', opts.dumpjson() + return f'{changed} settings changed.', opts.dumpjson() + + images_history = img_his.create_history_tabs(gr, opts) with gr.Blocks(analytics_enabled=False) as settings_interface: settings_submit = gr.Button(value="Apply settings", variant='primary') result = gr.HTML() @@ -1206,7 +1211,9 @@ def create_ui(wrap_gradio_gpu_call): (pnginfo_interface, "PNG Info", "pnginfo"), (modelmerger_interface, "Checkpoint Merger", "modelmerger"), (textual_inversion_interface, "Textual inversion", "ti"), + (images_history, "History", "images_history"), (settings_interface, "Settings", "settings"), + ] with open(os.path.join(script_path, "style.css"), "r", encoding="utf8") as file: diff --git a/repositorieslatent-diffusion b/repositorieslatent-diffusion new file mode 160000 index 000000000..abf33e700 --- /dev/null +++ b/repositorieslatent-diffusion @@ -0,0 +1 @@ +Subproject commit abf33e7002d59d9085081bce93ec798dcabd49af diff --git a/testui.py b/testui.py new file mode 100644 index 000000000..f54e4a622 --- /dev/null +++ b/testui.py @@ -0,0 +1,124 @@ +import os +import threading +import time +import importlib +import signal +import threading + +from modules.paths import script_path + +from modules import devices, sd_samplers +import modules.codeformer_model as codeformer +import modules.extras +import modules.face_restoration +import modules.gfpgan_model as gfpgan +import modules.img2img + +import modules.lowvram +import modules.paths +import modules.scripts +import modules.sd_hijack +import modules.sd_models +import modules.shared as shared +import modules.txt2img + +import modules.ui +from modules import devices +from modules import modelloader +from modules.paths import script_path +from modules.shared import cmd_opts + +modelloader.cleanup_models() +modules.sd_models.setup_model() +codeformer.setup_model(cmd_opts.codeformer_models_path) +gfpgan.setup_model(cmd_opts.gfpgan_models_path) +shared.face_restorers.append(modules.face_restoration.FaceRestoration()) +modelloader.load_upscalers() +queue_lock = threading.Lock() + + +def wrap_queued_call(func): + def f(*args, **kwargs): + with queue_lock: + res = func(*args, **kwargs) + + return res + + return f + + +def wrap_gradio_gpu_call(func, extra_outputs=None): + def f(*args, **kwargs): + devices.torch_gc() + + shared.state.sampling_step = 0 + shared.state.job_count = -1 + shared.state.job_no = 0 + shared.state.job_timestamp = shared.state.get_job_timestamp() + shared.state.current_latent = None + shared.state.current_image = None + shared.state.current_image_sampling_step = 0 + shared.state.interrupted = False + shared.state.textinfo = None + + with queue_lock: + res = func(*args, **kwargs) + + shared.state.job = "" + shared.state.job_count = 0 + + devices.torch_gc() + + return res + + return modules.ui.wrap_gradio_call(f, extra_outputs=extra_outputs) + + +modules.scripts.load_scripts(os.path.join(script_path, "scripts")) + +shared.sd_model = None #modules.sd_models.load_model() +#shared.opts.onchange("sd_model_checkpoint", wrap_queued_call(lambda: modules.sd_models.reload_model_weights(shared.sd_model))) + + +def webui(): + # make the program just exit at ctrl+c without waiting for anything + def sigint_handler(sig, frame): + print(f'Interrupted with signal {sig} in {frame}') + os._exit(0) + + signal.signal(signal.SIGINT, sigint_handler) + + while 1: + + demo = modules.ui.create_ui(wrap_gradio_gpu_call=wrap_gradio_gpu_call) + + demo.launch( + share=cmd_opts.share, + server_name="0.0.0.0" if cmd_opts.listen else None, + server_port=cmd_opts.port, + debug=cmd_opts.gradio_debug, + auth=[tuple(cred.split(':')) for cred in cmd_opts.gradio_auth.strip('"').split(',')] if cmd_opts.gradio_auth else None, + inbrowser=cmd_opts.autolaunch, + prevent_thread_lock=True + ) + + while 1: + time.sleep(0.5) + if getattr(demo, 'do_restart', False): + time.sleep(0.5) + demo.close() + time.sleep(0.5) + break + + sd_samplers.set_samplers() + + print('Reloading Custom Scripts') + modules.scripts.reload_scripts(os.path.join(script_path, "scripts")) + print('Reloading modules: modules.ui') + importlib.reload(modules.ui) + print('Restarting Gradio') + + + +if __name__ == "__main__": + webui() From 23f2989799ee3911d2959cfceb74b921f20c9a51 Mon Sep 17 00:00:00 2001 From: yfszzx Date: Mon, 10 Oct 2022 18:33:49 +0800 Subject: [PATCH 02/11] images history over --- javascript/images_history.js | 4 +- modules/images_history.py | 141 +++++++++++++++++++++-------------- modules/ui.py | 9 ++- testui.py | 124 ------------------------------ 4 files changed, 94 insertions(+), 184 deletions(-) delete mode 100644 testui.py diff --git a/javascript/images_history.js b/javascript/images_history.js index f30b7eff3..93d2b89ab 100644 --- a/javascript/images_history.js +++ b/javascript/images_history.js @@ -58,9 +58,9 @@ function set_history_index_from_img(e){ } } } -function images_history_get_current_img(is_image2image){ +function images_history_get_current_img(is_image2image, image_path, files){ head = is_image2image?"img2img":"txt2img" s = $(gradioApp().getElementById(head + '_images_history_set_index')).attr("img_index") - return s + return [s, image_path, files] } diff --git a/modules/images_history.py b/modules/images_history.py index 23d835573..0e0a48f3f 100644 --- a/modules/images_history.py +++ b/modules/images_history.py @@ -1,5 +1,6 @@ import os -def get_recent_images(is_img2img, dir_name, page_index, step): +def get_recent_images(dir_name, page_index, step, image_index): + print(image_index) page_index = int(page_index) f_list = os.listdir(dir_name) file_list = [] @@ -8,7 +9,7 @@ def get_recent_images(is_img2img, dir_name, page_index, step): continue file_list.append(file) file_list = sorted(file_list, key=lambda file: -os.path.getctime(os.path.join(dir_name, file))) - num = 24 + num = 48 max_page_index = len(file_list) // num + 1 page_index = max_page_index if page_index == -1 else page_index + step page_index = 1 if page_index < 1 else page_index @@ -16,75 +17,101 @@ def get_recent_images(is_img2img, dir_name, page_index, step): idx_frm = (page_index - 1) * num file_list = file_list[idx_frm:idx_frm + num] print(f"Loading history page {page_index}") - return [os.path.join(dir_name, file) for file in file_list], page_index, file_list -def first_page_click(is_img2img, dir_name): - return get_recent_images(is_img2img, dir_name, 1, 0) -def end_page_click(is_img2img, dir_name): - return get_recent_images(is_img2img, dir_name, -1, 0) -def prev_page_click(is_img2img, dir_name, page_index): - return get_recent_images(is_img2img, dir_name, page_index, -1) -def next_page_click(is_img2img, dir_name, page_index): - return get_recent_images(is_img2img, dir_name, page_index, 1) -def page_index_change(is_img2img, dir_name, page_index): - return get_recent_images(is_img2img, dir_name, page_index, 0) -def show_image_info(num, filenames): - return filenames[int(num)] -def delete_image(is_img2img, dir_name, name, page_index, filenames): + image_index = int(image_index) + if image_index < 0 or image_index > len(file_list) - 1: + current_file = None + hide_image = None + else: + current_file = file_list[int(image_index)] + hide_image = os.path.join(dir_name, current_file) + return [os.path.join(dir_name, file) for file in file_list], page_index, file_list, current_file, hide_image +def first_page_click(dir_name, page_index, image_index): + return get_recent_images(dir_name, 1, 0, image_index) +def end_page_click(dir_name, page_index, image_index): + return get_recent_images(dir_name, -1, 0, image_index) +def prev_page_click(dir_name, page_index, image_index): + return get_recent_images(dir_name, page_index, -1, image_index) +def next_page_click(dir_name, page_index, image_index): + return get_recent_images(dir_name, page_index, 1, image_index) +def page_index_change(dir_name, page_index, image_index): + return get_recent_images(dir_name, page_index, 0, image_index) + +def show_image_info(num, image_path, filenames): + file = filenames[int(num)] + return file, num, os.path.join(image_path, file) +def delete_image(is_img2img, dir_name, name, page_index, filenames, image_index): + print("filename", name) path = os.path.join(dir_name, name) if os.path.exists(path): print(f"Delete file {path}") os.remove(path) - i = 0 - for f in filenames: - if f == name: - break - i += 1 - images, page_index, file_list = get_recent_images(is_img2img, dir_name, page_index, 0) - current_file = file_list[i] if i < len(file_list) else None - return images, page_index, file_list, current_file + images, page_index, file_list, current_file, hide_image = get_recent_images(dir_name, page_index, 0, image_index) + return images, page_index, file_list, current_file, hide_image -def show_images_history(gr, opts, is_img2img): +def show_images_history(gr, opts, is_img2img, run_pnginfo, switch_dict): def id_name(is_img2img, name): return ("img2img" if is_img2img else "txt2img") + "_" + name - with gr.Row(): - if is_img2img: - dir_name = opts.outdir_img2img_samples - else: - dir_name = opts.outdir_txt2img_samples - first_page = gr.Button('First Page', elem_id=id_name(is_img2img,"images_history_first_page")) - prev_page = gr.Button('Prev Page') - page_index = gr.Number(value=1) - next_page = gr.Button('Next Page') - end_page = gr.Button('End Page') - with gr.Row(): - delete = gr.Button('Delete') - Send = gr.Button('Send') - with gr.Row(): - with gr.Column(elem_id=id_name(is_img2img,"images_history")): - history_gallery = gr.Gallery(label="Images history").style(grid=6) - img_file_name = gr.Textbox() - img_file_info = gr.Textbox(dir_name) - img_path = gr.Textbox(dir_name, visible=False) - set_index = gr.Button('set_index', elem_id=id_name(is_img2img,"images_history_set_index")) - is_img2img_flag = gr.Checkbox(is_img2img, visible=False) - filenames = gr.State() - first_page.click(first_page_click, inputs=[is_img2img_flag, img_path], outputs=[history_gallery, page_index, filenames]) - next_page.click(next_page_click, inputs=[is_img2img_flag, img_path, page_index], outputs=[history_gallery, page_index, filenames]) - prev_page.click(prev_page_click, inputs=[is_img2img_flag, img_path, page_index], outputs=[history_gallery, page_index, filenames]) - end_page.click(end_page_click, inputs=[is_img2img_flag, img_path], outputs=[history_gallery, page_index, filenames]) - page_index.submit(page_index_change, inputs=[is_img2img_flag, img_path, page_index], outputs=[history_gallery, page_index, filenames]) - set_index.click(show_image_info, _js="images_history_get_current_img",inputs=[is_img2img_flag, filenames], outputs=img_file_name) - delete.click(delete_image, inputs=[is_img2img_flag, img_path, img_file_name, page_index, filenames], outputs=[history_gallery, page_index, filenames,img_file_name]) + if is_img2img: + dir_name = opts.outdir_img2img_samples + else: + dir_name = opts.outdir_txt2img_samples + with gr.Row(): + first_page = gr.Button('First', elem_id=id_name(is_img2img,"images_history_first_page")) + prev_page = gr.Button('Prev') + page_index = gr.Number(value=1, label="Page Index") + next_page = gr.Button('Next') + end_page = gr.Button('End') + with gr.Row(elem_id=id_name(is_img2img,"images_history")): + with gr.Row(): + with gr.Column(): + history_gallery = gr.Gallery(show_label=False).style(grid=6) + with gr.Column(): + with gr.Row(): + delete = gr.Button('Delete') + pnginfo_send_to_txt2img = gr.Button('Send to txt2img') + pnginfo_send_to_img2img = gr.Button('Send to img2img') + with gr.Row(): + with gr.Column(): + img_file_info = gr.Textbox(dir_name, label="Generate Info") + img_file_name = gr.Textbox(label="File Name") + with gr.Row(): + # hiden items + img_path = gr.Textbox(dir_name, visible=False) + is_img2img_flag = gr.Checkbox(is_img2img, visible=False) + image_index = gr.Textbox(value=-1, visible=False) + set_index = gr.Button('set_index', elem_id=id_name(is_img2img,"images_history_set_index")) + filenames = gr.State() + hide_image = gr.Image(visible=False, type="pil") + info1 = gr.Textbox(visible=False) + info2 = gr.Textbox(visible=False) + + + # turn pages + gallery_inputs = [img_path, page_index, image_index] + gallery_outputs = [history_gallery, page_index, filenames, img_file_name, hide_image] + first_page.click(first_page_click, inputs=gallery_inputs, outputs=gallery_outputs) + next_page.click(next_page_click, inputs=gallery_inputs, outputs=gallery_outputs) + prev_page.click(prev_page_click, inputs=gallery_inputs, outputs=gallery_outputs) + end_page.click(end_page_click, inputs=gallery_inputs, outputs=gallery_outputs) + page_index.submit(page_index_change, inputs=gallery_inputs, outputs=gallery_outputs) #page_index.change(page_index_change, inputs=[is_img2img_flag, img_path, page_index], outputs=[history_gallery, page_index]) + + #other funcitons + set_index.click(show_image_info, _js="images_history_get_current_img", inputs=[is_img2img_flag, img_path, filenames], outputs=[img_file_name, image_index, hide_image]) + delete.click(delete_image, inputs=[is_img2img_flag, img_path, img_file_name, page_index, filenames, image_index], outputs=gallery_outputs) + hide_image.change(fn=run_pnginfo, inputs=[hide_image], outputs=[info1, img_file_info, info2]) + switch_dict["fn"](pnginfo_send_to_txt2img, switch_dict["t2i"], img_file_info, 'switch_to_txt2img') + switch_dict["fn"](pnginfo_send_to_img2img, switch_dict["i2i"], img_file_info, 'switch_to_img2img_img2img') + -def create_history_tabs(gr, opts): +def create_history_tabs(gr, opts, run_pnginfo, switch_dict): with gr.Blocks(analytics_enabled=False) as images_history: with gr.Tabs() as tabs: with gr.Tab("txt2img history", id="images_history_txt2img"): with gr.Blocks(analytics_enabled=False) as images_history_txt2img: - show_images_history(gr, opts, is_img2img=False) + show_images_history(gr, opts, False, run_pnginfo, switch_dict) with gr.Tab("img2img history", id="images_history_img2img"): with gr.Blocks(analytics_enabled=False) as images_history_img2img: - show_images_history(gr, opts, is_img2img=True) + show_images_history(gr, opts, True, run_pnginfo, switch_dict) return images_history diff --git a/modules/ui.py b/modules/ui.py index 8762fcf54..21c9236ba 100644 --- a/modules/ui.py +++ b/modules/ui.py @@ -1131,8 +1131,15 @@ def create_ui(wrap_gradio_gpu_call): return f'{changed} settings changed.', opts.dumpjson() + #images history + images_history_switch_dict = { + "fn":modules.generation_parameters_copypaste.connect_paste, + "t2i":txt2img_paste_fields, + "i2i":img2img_paste_fields + } + images_history = img_his.create_history_tabs(gr, opts, wrap_gradio_call(modules.extras.run_pnginfo), images_history_switch_dict) - images_history = img_his.create_history_tabs(gr, opts) + with gr.Blocks(analytics_enabled=False) as settings_interface: settings_submit = gr.Button(value="Apply settings", variant='primary') result = gr.HTML() diff --git a/testui.py b/testui.py deleted file mode 100644 index f54e4a622..000000000 --- a/testui.py +++ /dev/null @@ -1,124 +0,0 @@ -import os -import threading -import time -import importlib -import signal -import threading - -from modules.paths import script_path - -from modules import devices, sd_samplers -import modules.codeformer_model as codeformer -import modules.extras -import modules.face_restoration -import modules.gfpgan_model as gfpgan -import modules.img2img - -import modules.lowvram -import modules.paths -import modules.scripts -import modules.sd_hijack -import modules.sd_models -import modules.shared as shared -import modules.txt2img - -import modules.ui -from modules import devices -from modules import modelloader -from modules.paths import script_path -from modules.shared import cmd_opts - -modelloader.cleanup_models() -modules.sd_models.setup_model() -codeformer.setup_model(cmd_opts.codeformer_models_path) -gfpgan.setup_model(cmd_opts.gfpgan_models_path) -shared.face_restorers.append(modules.face_restoration.FaceRestoration()) -modelloader.load_upscalers() -queue_lock = threading.Lock() - - -def wrap_queued_call(func): - def f(*args, **kwargs): - with queue_lock: - res = func(*args, **kwargs) - - return res - - return f - - -def wrap_gradio_gpu_call(func, extra_outputs=None): - def f(*args, **kwargs): - devices.torch_gc() - - shared.state.sampling_step = 0 - shared.state.job_count = -1 - shared.state.job_no = 0 - shared.state.job_timestamp = shared.state.get_job_timestamp() - shared.state.current_latent = None - shared.state.current_image = None - shared.state.current_image_sampling_step = 0 - shared.state.interrupted = False - shared.state.textinfo = None - - with queue_lock: - res = func(*args, **kwargs) - - shared.state.job = "" - shared.state.job_count = 0 - - devices.torch_gc() - - return res - - return modules.ui.wrap_gradio_call(f, extra_outputs=extra_outputs) - - -modules.scripts.load_scripts(os.path.join(script_path, "scripts")) - -shared.sd_model = None #modules.sd_models.load_model() -#shared.opts.onchange("sd_model_checkpoint", wrap_queued_call(lambda: modules.sd_models.reload_model_weights(shared.sd_model))) - - -def webui(): - # make the program just exit at ctrl+c without waiting for anything - def sigint_handler(sig, frame): - print(f'Interrupted with signal {sig} in {frame}') - os._exit(0) - - signal.signal(signal.SIGINT, sigint_handler) - - while 1: - - demo = modules.ui.create_ui(wrap_gradio_gpu_call=wrap_gradio_gpu_call) - - demo.launch( - share=cmd_opts.share, - server_name="0.0.0.0" if cmd_opts.listen else None, - server_port=cmd_opts.port, - debug=cmd_opts.gradio_debug, - auth=[tuple(cred.split(':')) for cred in cmd_opts.gradio_auth.strip('"').split(',')] if cmd_opts.gradio_auth else None, - inbrowser=cmd_opts.autolaunch, - prevent_thread_lock=True - ) - - while 1: - time.sleep(0.5) - if getattr(demo, 'do_restart', False): - time.sleep(0.5) - demo.close() - time.sleep(0.5) - break - - sd_samplers.set_samplers() - - print('Reloading Custom Scripts') - modules.scripts.reload_scripts(os.path.join(script_path, "scripts")) - print('Reloading modules: modules.ui') - importlib.reload(modules.ui) - print('Restarting Gradio') - - - -if __name__ == "__main__": - webui() From 7b1db45e1fda8603d4617affd976066be5e5b821 Mon Sep 17 00:00:00 2001 From: yfszzx Date: Tue, 11 Oct 2022 20:17:27 +0800 Subject: [PATCH 03/11] images history improvement --- javascript/images_history.js | 178 ++++++++++++++++--------- javascript/jquery-3.6.0.min.js | 2 - modules/images_history.py | 229 +++++++++++++++++---------------- style.css | 3 + 4 files changed, 242 insertions(+), 170 deletions(-) delete mode 100644 javascript/jquery-3.6.0.min.js diff --git a/javascript/images_history.js b/javascript/images_history.js index 93d2b89ab..9a3e00a00 100644 --- a/javascript/images_history.js +++ b/javascript/images_history.js @@ -1,66 +1,124 @@ -function init_images_history(){ - if (gradioApp().getElementById('txt2img_images_history_first_page') == null) { - setTimeout(init_images_history, 1000) - } else { - tab_list = ["txt2img", "img2img"] - for (i in tab_list){ - tab = tab_list[i] - gradioApp().getElementById(tab + "_images_history_first_page").click() - $(gradioApp().getElementById(tab + '_images_history')).addClass("images_history_gallery") - item = $(gradioApp().getElementById(tab + '_images_history_set_index')) - item.addClass("images_history_set_index") - item.hide() - } - } - +images_history_tab_list = ["txt2img", "img2img", "extras"] +function images_history_init(){ + if (gradioApp().getElementById('txt2img_images_history_first_page') == null) { + setTimeout(images_history_init, 500) + } else { + for (i in images_history_tab_list ){ + tab = images_history_tab_list[i] + gradioApp().getElementById(tab + '_images_history').classList.add("images_history_gallery") + gradioApp().getElementById(tab + '_images_history_set_index').classList.add("images_history_set_index") + + } + gradioApp().getElementById("txt2img_images_history_first_page").click() + } +} +setTimeout(images_history_init, 500) +var images_history_button_actions = function(){ + if (!this.classList.contains("transform")){ + gallery = this.parentElement + while(!gallery.classList.contains("images_history_gallery")){gallery = gallery.parentElement} + buttons = gallery.querySelectorAll(".gallery-item") + i = 0 + hidden_list = [] + buttons.forEach(function(e){ + if (e.style.display == "none"){ + hidden_list.push(i) + } + i += 1 + }) + if (hidden_list.length > 0){ + setTimeout(images_history_hide_buttons, 10, hidden_list, gallery) + } + + } + images_history_set_image_info(this) + } -setTimeout(init_images_history, 1000) onUiUpdate(function(){ - fullImg_preview = gradioApp().querySelectorAll('#txt2img_images_history img.w-full') - if(fullImg_preview.length > 0){ - fullImg_preview.forEach(set_history_index_from_img); - } - fullImg_preview = gradioApp().querySelectorAll('#img2img_images_history img.w-full') - if(fullImg_preview.length > 0){ - fullImg_preview.forEach(set_history_index_from_img); + for (i in images_history_tab_list ){ + tab = images_history_tab_list[i] + buttons = gradioApp().querySelectorAll('#' + tab + '_images_history .gallery-item') + buttons.forEach(function(bnt){ + bnt.addEventListener('click', images_history_button_actions, true) + }); } }) - -function set_history_gallery_index(item){ - buttons = item.find(".gallery-item") - // alert(item.attr("id") + " " + buttons.length) - index = -1 - i = 0 - buttons.each(function(){ - if($(this).hasClass("!ring-2")){ index = i } - i += 1 - }) - if (index == -1){ - setTimeout(set_history_gallery_index, 10, item) - } else { - item = item.find(".images_history_set_index").first() - item.attr("img_index", index) - item.click() - } -} -function set_history_index_from_img(e){ - if(e && e.parentElement.tagName == 'BUTTON'){ - bnt = $(e).parent() - if (bnt.hasClass("transform")){ - bnt.off("click").on("click",function(){ - set_history_gallery_index($(this).parents(".images_history_gallery").first()) - }) - } else { - bnt.off("mousedown").on("mousedown", function(){ - set_history_gallery_index($(this).parents(".images_history_gallery").first()) - }) - - } - } -} -function images_history_get_current_img(is_image2image, image_path, files){ - head = is_image2image?"img2img":"txt2img" - s = $(gradioApp().getElementById(head + '_images_history_set_index')).attr("img_index") - return [s, image_path, files] +function images_history_hide_buttons(hidden_list, gallery){ + buttons = gallery.querySelectorAll(".gallery-item") + num = 0 + buttons.forEach(function(e){ + if (e.style.display == "none"){ + num += 1 + } + }) + if (num == hidden_list.length){ + setTimeout(images_history_hide_buttons, 10, hidden_list, gallery) + } + for( i in hidden_list){ + buttons[hidden_list[i]].style.display = "none" + } } +function images_history_set_image_info(button){ + item = button.parentElement + while(item.tagName != "DIV"){item = item.parentElement} + buttons = item.querySelectorAll(".gallery-item") + index = -1 + i = 0 + buttons.forEach(function(e){ + if(e==button){index = i} + if(e.style.display != "none"){ + i += 1 + } + }) + gallery = button.parentElement + while(!gallery.classList.contains("images_history_gallery")){gallery = gallery.parentElement} + set_btn = gallery.querySelector(".images_history_set_index") + set_btn.setAttribute("img_index", index) + set_btn.click() +} + +function images_history_get_current_img(tabname, image_path, files){ + s = gradioApp().getElementById(tabname + '_images_history_set_index').getAttribute("img_index") + return [s, image_path, files] +} + +function images_history_delete(tabname, img_path, img_file_name, page_index, filenames, image_index){ + image_index = parseInt(image_index) + tab = gradioApp().getElementById(tabname + '_images_history') + set_btn = tab.querySelector(".images_history_set_index") + buttons = [] + tab.querySelectorAll(".gallery-item").forEach(function(e){ + if (e.style.display != 'none'){ + buttons.push(e) + } + }) + + + img_num = buttons.length / 2 + if (img_num == 1){ + setTimeout(function(tabname){ + gradioApp().getElementById(tabname + '_images_history_renew_page').click() + }, 30, tabname) + } else { + buttons[image_index].style.display = 'none' + buttons[image_index + img_num].style.display = 'none' + if (image_index >= img_num - 1){ + console.log(buttons.length, img_num) + btn = buttons[img_num - 2] + } else { + btn = buttons[image_index + 1] + } + setTimeout(function(btn){btn.click()}, 30, btn) + } + + return [tabname, img_path, img_file_name, page_index, filenames, image_index] +} + +function images_history_turnpage(img_path, page_index, image_index, tabname){ + buttons = gradioApp().getElementById(tabname + '_images_history').querySelectorAll(".gallery-item") + buttons.forEach(function(elem) { + elem.style.display = 'block' + }) + return [img_path, page_index, image_index, tabname] +} diff --git a/javascript/jquery-3.6.0.min.js b/javascript/jquery-3.6.0.min.js deleted file mode 100644 index c4c6022f2..000000000 --- a/javascript/jquery-3.6.0.min.js +++ /dev/null @@ -1,2 +0,0 @@ -/*! jQuery v3.6.0 | (c) OpenJS Foundation and other contributors | jquery.org/license */ -!function(e,t){"use strict";"object"==typeof module&&"object"==typeof module.exports?module.exports=e.document?t(e,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return t(e)}:t(e)}("undefined"!=typeof window?window:this,function(C,e){"use strict";var t=[],r=Object.getPrototypeOf,s=t.slice,g=t.flat?function(e){return t.flat.call(e)}:function(e){return t.concat.apply([],e)},u=t.push,i=t.indexOf,n={},o=n.toString,v=n.hasOwnProperty,a=v.toString,l=a.call(Object),y={},m=function(e){return"function"==typeof e&&"number"!=typeof e.nodeType&&"function"!=typeof e.item},x=function(e){return null!=e&&e===e.window},E=C.document,c={type:!0,src:!0,nonce:!0,noModule:!0};function b(e,t,n){var r,i,o=(n=n||E).createElement("script");if(o.text=e,t)for(r in c)(i=t[r]||t.getAttribute&&t.getAttribute(r))&&o.setAttribute(r,i);n.head.appendChild(o).parentNode.removeChild(o)}function w(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?n[o.call(e)]||"object":typeof e}var f="3.6.0",S=function(e,t){return new S.fn.init(e,t)};function p(e){var t=!!e&&"length"in e&&e.length,n=w(e);return!m(e)&&!x(e)&&("array"===n||0===t||"number"==typeof t&&0+~]|"+M+")"+M+"*"),U=new RegExp(M+"|>"),X=new RegExp(F),V=new RegExp("^"+I+"$"),G={ID:new RegExp("^#("+I+")"),CLASS:new RegExp("^\\.("+I+")"),TAG:new RegExp("^("+I+"|[*])"),ATTR:new RegExp("^"+W),PSEUDO:new RegExp("^"+F),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+R+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Y=/HTML$/i,Q=/^(?:input|select|textarea|button)$/i,J=/^h\d$/i,K=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ee=/[+~]/,te=new RegExp("\\\\[\\da-fA-F]{1,6}"+M+"?|\\\\([^\\r\\n\\f])","g"),ne=function(e,t){var n="0x"+e.slice(1)-65536;return t||(n<0?String.fromCharCode(n+65536):String.fromCharCode(n>>10|55296,1023&n|56320))},re=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,ie=function(e,t){return t?"\0"===e?"\ufffd":e.slice(0,-1)+"\\"+e.charCodeAt(e.length-1).toString(16)+" ":"\\"+e},oe=function(){T()},ae=be(function(e){return!0===e.disabled&&"fieldset"===e.nodeName.toLowerCase()},{dir:"parentNode",next:"legend"});try{H.apply(t=O.call(p.childNodes),p.childNodes),t[p.childNodes.length].nodeType}catch(e){H={apply:t.length?function(e,t){L.apply(e,O.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function se(t,e,n,r){var i,o,a,s,u,l,c,f=e&&e.ownerDocument,p=e?e.nodeType:9;if(n=n||[],"string"!=typeof t||!t||1!==p&&9!==p&&11!==p)return n;if(!r&&(T(e),e=e||C,E)){if(11!==p&&(u=Z.exec(t)))if(i=u[1]){if(9===p){if(!(a=e.getElementById(i)))return n;if(a.id===i)return n.push(a),n}else if(f&&(a=f.getElementById(i))&&y(e,a)&&a.id===i)return n.push(a),n}else{if(u[2])return H.apply(n,e.getElementsByTagName(t)),n;if((i=u[3])&&d.getElementsByClassName&&e.getElementsByClassName)return H.apply(n,e.getElementsByClassName(i)),n}if(d.qsa&&!N[t+" "]&&(!v||!v.test(t))&&(1!==p||"object"!==e.nodeName.toLowerCase())){if(c=t,f=e,1===p&&(U.test(t)||z.test(t))){(f=ee.test(t)&&ye(e.parentNode)||e)===e&&d.scope||((s=e.getAttribute("id"))?s=s.replace(re,ie):e.setAttribute("id",s=S)),o=(l=h(t)).length;while(o--)l[o]=(s?"#"+s:":scope")+" "+xe(l[o]);c=l.join(",")}try{return H.apply(n,f.querySelectorAll(c)),n}catch(e){N(t,!0)}finally{s===S&&e.removeAttribute("id")}}}return g(t.replace($,"$1"),e,n,r)}function ue(){var r=[];return function e(t,n){return r.push(t+" ")>b.cacheLength&&delete e[r.shift()],e[t+" "]=n}}function le(e){return e[S]=!0,e}function ce(e){var t=C.createElement("fieldset");try{return!!e(t)}catch(e){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function fe(e,t){var n=e.split("|"),r=n.length;while(r--)b.attrHandle[n[r]]=t}function pe(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&e.sourceIndex-t.sourceIndex;if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function de(t){return function(e){return"input"===e.nodeName.toLowerCase()&&e.type===t}}function he(n){return function(e){var t=e.nodeName.toLowerCase();return("input"===t||"button"===t)&&e.type===n}}function ge(t){return function(e){return"form"in e?e.parentNode&&!1===e.disabled?"label"in e?"label"in e.parentNode?e.parentNode.disabled===t:e.disabled===t:e.isDisabled===t||e.isDisabled!==!t&&ae(e)===t:e.disabled===t:"label"in e&&e.disabled===t}}function ve(a){return le(function(o){return o=+o,le(function(e,t){var n,r=a([],e.length,o),i=r.length;while(i--)e[n=r[i]]&&(e[n]=!(t[n]=e[n]))})})}function ye(e){return e&&"undefined"!=typeof e.getElementsByTagName&&e}for(e in d=se.support={},i=se.isXML=function(e){var t=e&&e.namespaceURI,n=e&&(e.ownerDocument||e).documentElement;return!Y.test(t||n&&n.nodeName||"HTML")},T=se.setDocument=function(e){var t,n,r=e?e.ownerDocument||e:p;return r!=C&&9===r.nodeType&&r.documentElement&&(a=(C=r).documentElement,E=!i(C),p!=C&&(n=C.defaultView)&&n.top!==n&&(n.addEventListener?n.addEventListener("unload",oe,!1):n.attachEvent&&n.attachEvent("onunload",oe)),d.scope=ce(function(e){return a.appendChild(e).appendChild(C.createElement("div")),"undefined"!=typeof e.querySelectorAll&&!e.querySelectorAll(":scope fieldset div").length}),d.attributes=ce(function(e){return e.className="i",!e.getAttribute("className")}),d.getElementsByTagName=ce(function(e){return e.appendChild(C.createComment("")),!e.getElementsByTagName("*").length}),d.getElementsByClassName=K.test(C.getElementsByClassName),d.getById=ce(function(e){return a.appendChild(e).id=S,!C.getElementsByName||!C.getElementsByName(S).length}),d.getById?(b.filter.ID=function(e){var t=e.replace(te,ne);return function(e){return e.getAttribute("id")===t}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&E){var n=t.getElementById(e);return n?[n]:[]}}):(b.filter.ID=function(e){var n=e.replace(te,ne);return function(e){var t="undefined"!=typeof e.getAttributeNode&&e.getAttributeNode("id");return t&&t.value===n}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&E){var n,r,i,o=t.getElementById(e);if(o){if((n=o.getAttributeNode("id"))&&n.value===e)return[o];i=t.getElementsByName(e),r=0;while(o=i[r++])if((n=o.getAttributeNode("id"))&&n.value===e)return[o]}return[]}}),b.find.TAG=d.getElementsByTagName?function(e,t){return"undefined"!=typeof t.getElementsByTagName?t.getElementsByTagName(e):d.qsa?t.querySelectorAll(e):void 0}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},b.find.CLASS=d.getElementsByClassName&&function(e,t){if("undefined"!=typeof t.getElementsByClassName&&E)return t.getElementsByClassName(e)},s=[],v=[],(d.qsa=K.test(C.querySelectorAll))&&(ce(function(e){var t;a.appendChild(e).innerHTML="",e.querySelectorAll("[msallowcapture^='']").length&&v.push("[*^$]="+M+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||v.push("\\["+M+"*(?:value|"+R+")"),e.querySelectorAll("[id~="+S+"-]").length||v.push("~="),(t=C.createElement("input")).setAttribute("name",""),e.appendChild(t),e.querySelectorAll("[name='']").length||v.push("\\["+M+"*name"+M+"*="+M+"*(?:''|\"\")"),e.querySelectorAll(":checked").length||v.push(":checked"),e.querySelectorAll("a#"+S+"+*").length||v.push(".#.+[+~]"),e.querySelectorAll("\\\f"),v.push("[\\r\\n\\f]")}),ce(function(e){e.innerHTML="";var t=C.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&v.push("name"+M+"*[*^$|!~]?="),2!==e.querySelectorAll(":enabled").length&&v.push(":enabled",":disabled"),a.appendChild(e).disabled=!0,2!==e.querySelectorAll(":disabled").length&&v.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),v.push(",.*:")})),(d.matchesSelector=K.test(c=a.matches||a.webkitMatchesSelector||a.mozMatchesSelector||a.oMatchesSelector||a.msMatchesSelector))&&ce(function(e){d.disconnectedMatch=c.call(e,"*"),c.call(e,"[s!='']:x"),s.push("!=",F)}),v=v.length&&new RegExp(v.join("|")),s=s.length&&new RegExp(s.join("|")),t=K.test(a.compareDocumentPosition),y=t||K.test(a.contains)?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},j=t?function(e,t){if(e===t)return l=!0,0;var n=!e.compareDocumentPosition-!t.compareDocumentPosition;return n||(1&(n=(e.ownerDocument||e)==(t.ownerDocument||t)?e.compareDocumentPosition(t):1)||!d.sortDetached&&t.compareDocumentPosition(e)===n?e==C||e.ownerDocument==p&&y(p,e)?-1:t==C||t.ownerDocument==p&&y(p,t)?1:u?P(u,e)-P(u,t):0:4&n?-1:1)}:function(e,t){if(e===t)return l=!0,0;var n,r=0,i=e.parentNode,o=t.parentNode,a=[e],s=[t];if(!i||!o)return e==C?-1:t==C?1:i?-1:o?1:u?P(u,e)-P(u,t):0;if(i===o)return pe(e,t);n=e;while(n=n.parentNode)a.unshift(n);n=t;while(n=n.parentNode)s.unshift(n);while(a[r]===s[r])r++;return r?pe(a[r],s[r]):a[r]==p?-1:s[r]==p?1:0}),C},se.matches=function(e,t){return se(e,null,null,t)},se.matchesSelector=function(e,t){if(T(e),d.matchesSelector&&E&&!N[t+" "]&&(!s||!s.test(t))&&(!v||!v.test(t)))try{var n=c.call(e,t);if(n||d.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(e){N(t,!0)}return 0":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(te,ne),e[3]=(e[3]||e[4]||e[5]||"").replace(te,ne),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||se.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&se.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return G.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&X.test(n)&&(t=h(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(te,ne).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=m[e+" "];return t||(t=new RegExp("(^|"+M+")"+e+"("+M+"|$)"))&&m(e,function(e){return t.test("string"==typeof e.className&&e.className||"undefined"!=typeof e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(n,r,i){return function(e){var t=se.attr(e,n);return null==t?"!="===r:!r||(t+="","="===r?t===i:"!="===r?t!==i:"^="===r?i&&0===t.indexOf(i):"*="===r?i&&-1:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i;function j(e,n,r){return m(n)?S.grep(e,function(e,t){return!!n.call(e,t,e)!==r}):n.nodeType?S.grep(e,function(e){return e===n!==r}):"string"!=typeof n?S.grep(e,function(e){return-1)[^>]*|#([\w-]+))$/;(S.fn.init=function(e,t,n){var r,i;if(!e)return this;if(n=n||D,"string"==typeof e){if(!(r="<"===e[0]&&">"===e[e.length-1]&&3<=e.length?[null,e,null]:q.exec(e))||!r[1]&&t)return!t||t.jquery?(t||n).find(e):this.constructor(t).find(e);if(r[1]){if(t=t instanceof S?t[0]:t,S.merge(this,S.parseHTML(r[1],t&&t.nodeType?t.ownerDocument||t:E,!0)),N.test(r[1])&&S.isPlainObject(t))for(r in t)m(this[r])?this[r](t[r]):this.attr(r,t[r]);return this}return(i=E.getElementById(r[2]))&&(this[0]=i,this.length=1),this}return e.nodeType?(this[0]=e,this.length=1,this):m(e)?void 0!==n.ready?n.ready(e):e(S):S.makeArray(e,this)}).prototype=S.fn,D=S(E);var L=/^(?:parents|prev(?:Until|All))/,H={children:!0,contents:!0,next:!0,prev:!0};function O(e,t){while((e=e[t])&&1!==e.nodeType);return e}S.fn.extend({has:function(e){var t=S(e,this),n=t.length;return this.filter(function(){for(var e=0;e\x20\t\r\n\f]*)/i,he=/^$|^module$|\/(?:java|ecma)script/i;ce=E.createDocumentFragment().appendChild(E.createElement("div")),(fe=E.createElement("input")).setAttribute("type","radio"),fe.setAttribute("checked","checked"),fe.setAttribute("name","t"),ce.appendChild(fe),y.checkClone=ce.cloneNode(!0).cloneNode(!0).lastChild.checked,ce.innerHTML="",y.noCloneChecked=!!ce.cloneNode(!0).lastChild.defaultValue,ce.innerHTML="",y.option=!!ce.lastChild;var ge={thead:[1,"","
"],col:[2,"","
"],tr:[2,"","
"],td:[3,"","
"],_default:[0,"",""]};function ve(e,t){var n;return n="undefined"!=typeof e.getElementsByTagName?e.getElementsByTagName(t||"*"):"undefined"!=typeof e.querySelectorAll?e.querySelectorAll(t||"*"):[],void 0===t||t&&A(e,t)?S.merge([e],n):n}function ye(e,t){for(var n=0,r=e.length;n",""]);var me=/<|&#?\w+;/;function xe(e,t,n,r,i){for(var o,a,s,u,l,c,f=t.createDocumentFragment(),p=[],d=0,h=e.length;d\s*$/g;function je(e,t){return A(e,"table")&&A(11!==t.nodeType?t:t.firstChild,"tr")&&S(e).children("tbody")[0]||e}function De(e){return e.type=(null!==e.getAttribute("type"))+"/"+e.type,e}function qe(e){return"true/"===(e.type||"").slice(0,5)?e.type=e.type.slice(5):e.removeAttribute("type"),e}function Le(e,t){var n,r,i,o,a,s;if(1===t.nodeType){if(Y.hasData(e)&&(s=Y.get(e).events))for(i in Y.remove(t,"handle events"),s)for(n=0,r=s[i].length;n").attr(n.scriptAttrs||{}).prop({charset:n.scriptCharset,src:n.url}).on("load error",i=function(e){r.remove(),i=null,e&&t("error"===e.type?404:200,e.type)}),E.head.appendChild(r[0])},abort:function(){i&&i()}}});var _t,zt=[],Ut=/(=)\?(?=&|$)|\?\?/;S.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=zt.pop()||S.expando+"_"+wt.guid++;return this[e]=!0,e}}),S.ajaxPrefilter("json jsonp",function(e,t,n){var r,i,o,a=!1!==e.jsonp&&(Ut.test(e.url)?"url":"string"==typeof e.data&&0===(e.contentType||"").indexOf("application/x-www-form-urlencoded")&&Ut.test(e.data)&&"data");if(a||"jsonp"===e.dataTypes[0])return r=e.jsonpCallback=m(e.jsonpCallback)?e.jsonpCallback():e.jsonpCallback,a?e[a]=e[a].replace(Ut,"$1"+r):!1!==e.jsonp&&(e.url+=(Tt.test(e.url)?"&":"?")+e.jsonp+"="+r),e.converters["script json"]=function(){return o||S.error(r+" was not called"),o[0]},e.dataTypes[0]="json",i=C[r],C[r]=function(){o=arguments},n.always(function(){void 0===i?S(C).removeProp(r):C[r]=i,e[r]&&(e.jsonpCallback=t.jsonpCallback,zt.push(r)),o&&m(i)&&i(o[0]),o=i=void 0}),"script"}),y.createHTMLDocument=((_t=E.implementation.createHTMLDocument("").body).innerHTML="
",2===_t.childNodes.length),S.parseHTML=function(e,t,n){return"string"!=typeof e?[]:("boolean"==typeof t&&(n=t,t=!1),t||(y.createHTMLDocument?((r=(t=E.implementation.createHTMLDocument("")).createElement("base")).href=E.location.href,t.head.appendChild(r)):t=E),o=!n&&[],(i=N.exec(e))?[t.createElement(i[1])]:(i=xe([e],t,o),o&&o.length&&S(o).remove(),S.merge([],i.childNodes)));var r,i,o},S.fn.load=function(e,t,n){var r,i,o,a=this,s=e.indexOf(" ");return-1").append(S.parseHTML(e)).find(r):e)}).always(n&&function(e,t){a.each(function(){n.apply(this,o||[e.responseText,t,e])})}),this},S.expr.pseudos.animated=function(t){return S.grep(S.timers,function(e){return t===e.elem}).length},S.offset={setOffset:function(e,t,n){var r,i,o,a,s,u,l=S.css(e,"position"),c=S(e),f={};"static"===l&&(e.style.position="relative"),s=c.offset(),o=S.css(e,"top"),u=S.css(e,"left"),("absolute"===l||"fixed"===l)&&-1<(o+u).indexOf("auto")?(a=(r=c.position()).top,i=r.left):(a=parseFloat(o)||0,i=parseFloat(u)||0),m(t)&&(t=t.call(e,n,S.extend({},s))),null!=t.top&&(f.top=t.top-s.top+a),null!=t.left&&(f.left=t.left-s.left+i),"using"in t?t.using.call(e,f):c.css(f)}},S.fn.extend({offset:function(t){if(arguments.length)return void 0===t?this:this.each(function(e){S.offset.setOffset(this,t,e)});var e,n,r=this[0];return r?r.getClientRects().length?(e=r.getBoundingClientRect(),n=r.ownerDocument.defaultView,{top:e.top+n.pageYOffset,left:e.left+n.pageXOffset}):{top:0,left:0}:void 0},position:function(){if(this[0]){var e,t,n,r=this[0],i={top:0,left:0};if("fixed"===S.css(r,"position"))t=r.getBoundingClientRect();else{t=this.offset(),n=r.ownerDocument,e=r.offsetParent||n.documentElement;while(e&&(e===n.body||e===n.documentElement)&&"static"===S.css(e,"position"))e=e.parentNode;e&&e!==r&&1===e.nodeType&&((i=S(e).offset()).top+=S.css(e,"borderTopWidth",!0),i.left+=S.css(e,"borderLeftWidth",!0))}return{top:t.top-i.top-S.css(r,"marginTop",!0),left:t.left-i.left-S.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent;while(e&&"static"===S.css(e,"position"))e=e.offsetParent;return e||re})}}),S.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(t,i){var o="pageYOffset"===i;S.fn[t]=function(e){return $(this,function(e,t,n){var r;if(x(e)?r=e:9===e.nodeType&&(r=e.defaultView),void 0===n)return r?r[i]:e[t];r?r.scrollTo(o?r.pageXOffset:n,o?n:r.pageYOffset):e[t]=n},t,e,arguments.length)}}),S.each(["top","left"],function(e,n){S.cssHooks[n]=Fe(y.pixelPosition,function(e,t){if(t)return t=We(e,n),Pe.test(t)?S(e).position()[n]+"px":t})}),S.each({Height:"height",Width:"width"},function(a,s){S.each({padding:"inner"+a,content:s,"":"outer"+a},function(r,o){S.fn[o]=function(e,t){var n=arguments.length&&(r||"boolean"!=typeof e),i=r||(!0===e||!0===t?"margin":"border");return $(this,function(e,t,n){var r;return x(e)?0===o.indexOf("outer")?e["inner"+a]:e.document.documentElement["client"+a]:9===e.nodeType?(r=e.documentElement,Math.max(e.body["scroll"+a],r["scroll"+a],e.body["offset"+a],r["offset"+a],r["client"+a])):void 0===n?S.css(e,t,i):S.style(e,t,n,i)},s,n?e:void 0,n)}})}),S.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){S.fn[t]=function(e){return this.on(t,e)}}),S.fn.extend({bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)},hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)}}),S.each("blur focus focusin focusout resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu".split(" "),function(e,n){S.fn[n]=function(e,t){return 0 max_page_index else page_index - idx_frm = (page_index - 1) * num - file_list = file_list[idx_frm:idx_frm + num] - print(f"Loading history page {page_index}") - image_index = int(image_index) - if image_index < 0 or image_index > len(file_list) - 1: - current_file = None - hide_image = None - else: - current_file = file_list[int(image_index)] - hide_image = os.path.join(dir_name, current_file) - return [os.path.join(dir_name, file) for file in file_list], page_index, file_list, current_file, hide_image -def first_page_click(dir_name, page_index, image_index): - return get_recent_images(dir_name, 1, 0, image_index) -def end_page_click(dir_name, page_index, image_index): - return get_recent_images(dir_name, -1, 0, image_index) -def prev_page_click(dir_name, page_index, image_index): - return get_recent_images(dir_name, page_index, -1, image_index) -def next_page_click(dir_name, page_index, image_index): - return get_recent_images(dir_name, page_index, 1, image_index) -def page_index_change(dir_name, page_index, image_index): - return get_recent_images(dir_name, page_index, 0, image_index) + #print(image_index) + page_index = int(page_index) + f_list = os.listdir(dir_name) + file_list = [] + for file in f_list: + if file[-4:] == ".txt": + continue + file_list.append(file) + file_list = sorted(file_list, key=lambda file: -os.path.getctime(os.path.join(dir_name, file))) + num = 48 + max_page_index = len(file_list) // num + 1 + page_index = max_page_index if page_index == -1 else page_index + step + page_index = 1 if page_index < 1 else page_index + page_index = max_page_index if page_index > max_page_index else page_index + idx_frm = (page_index - 1) * num + file_list = file_list[idx_frm:idx_frm + num] + #print(f"Loading history page {page_index}") + image_index = int(image_index) + if image_index < 0 or image_index > len(file_list) - 1: + current_file = None + hide_image = None + else: + current_file = file_list[int(image_index)] + hide_image = os.path.join(dir_name, current_file) + return [os.path.join(dir_name, file) for file in file_list], page_index, file_list, current_file, hide_image +def first_page_click(dir_name, page_index, image_index, tabname): + return get_recent_images(dir_name, 1, 0, image_index) +def end_page_click(dir_name, page_index, image_index, tabname): + return get_recent_images(dir_name, -1, 0, image_index) +def prev_page_click(dir_name, page_index, image_index, tabname): + return get_recent_images(dir_name, page_index, -1, image_index) +def next_page_click(dir_name, page_index, image_index, tabname): + return get_recent_images(dir_name, page_index, 1, image_index) +def page_index_change(dir_name, page_index, image_index, tabname): + return get_recent_images(dir_name, page_index, 0, image_index) def show_image_info(num, image_path, filenames): - file = filenames[int(num)] - return file, num, os.path.join(image_path, file) -def delete_image(is_img2img, dir_name, name, page_index, filenames, image_index): - print("filename", name) - path = os.path.join(dir_name, name) - if os.path.exists(path): - print(f"Delete file {path}") - os.remove(path) - images, page_index, file_list, current_file, hide_image = get_recent_images(dir_name, page_index, 0, image_index) - return images, page_index, file_list, current_file, hide_image + #print("set img",num) + file = filenames[int(num)] + return file, num, os.path.join(image_path, file) +def delete_image(tabname, dir_name, name, page_index, filenames, image_index): + #print("filename", name) + path = os.path.join(dir_name, name) + if os.path.exists(path): + print(f"Delete file {path}") + os.remove(path) + new_file_list = [] + for f in filenames: + if f == name: + continue + new_file_list.append(f) + else: + print(f"Not exists file {path}") + new_file_list = filenames + return page_index, new_file_list +def show_images_history(gr, opts, tabname, run_pnginfo, switch_dict): + if tabname == "txt2img": + dir_name = opts.outdir_txt2img_samples + elif tabname == "img2img": + dir_name = opts.outdir_img2img_samples + elif tabname == "extras": + dir_name = opts.outdir_extras_samples + with gr.Row(): + renew_page = gr.Button('Renew', elem_id=tabname + "_images_history_renew_page") + first_page = gr.Button('First', elem_id=tabname + "_images_history_first_page") + prev_page = gr.Button('Prev') + page_index = gr.Number(value=1, label="Page Index") + next_page = gr.Button('Next', elem_id=tabname + "_images_history_next_page") + end_page = gr.Button('End') + with gr.Row(elem_id=tabname + "_images_history"): + with gr.Row(): + with gr.Column(): + history_gallery = gr.Gallery(show_label=False).style(grid=6) + with gr.Column(): + with gr.Row(): + delete = gr.Button('Delete') + pnginfo_send_to_txt2img = gr.Button('Send to txt2img') + pnginfo_send_to_img2img = gr.Button('Send to img2img') + with gr.Row(): + with gr.Column(): + img_file_info = gr.Textbox(label="Generate Info") + img_file_name = gr.Textbox(label="File Name") + with gr.Row(): + # hiden items + img_path = gr.Textbox(dir_name, visible=False) + tabname_box = gr.Textbox(tabname, visible=False) + image_index = gr.Textbox(value=-1, visible=False) + set_index = gr.Button('set_index', elem_id=tabname + "_images_history_set_index", visible=False) + filenames = gr.State() + hide_image = gr.Image(visible=False, type="pil") + info1 = gr.Textbox(visible=False) + info2 = gr.Textbox(visible=False) -def show_images_history(gr, opts, is_img2img, run_pnginfo, switch_dict): - def id_name(is_img2img, name): - return ("img2img" if is_img2img else "txt2img") + "_" + name - if is_img2img: - dir_name = opts.outdir_img2img_samples - else: - dir_name = opts.outdir_txt2img_samples - with gr.Row(): - first_page = gr.Button('First', elem_id=id_name(is_img2img,"images_history_first_page")) - prev_page = gr.Button('Prev') - page_index = gr.Number(value=1, label="Page Index") - next_page = gr.Button('Next') - end_page = gr.Button('End') - with gr.Row(elem_id=id_name(is_img2img,"images_history")): - with gr.Row(): - with gr.Column(): - history_gallery = gr.Gallery(show_label=False).style(grid=6) - with gr.Column(): - with gr.Row(): - delete = gr.Button('Delete') - pnginfo_send_to_txt2img = gr.Button('Send to txt2img') - pnginfo_send_to_img2img = gr.Button('Send to img2img') - with gr.Row(): - with gr.Column(): - img_file_info = gr.Textbox(dir_name, label="Generate Info") - img_file_name = gr.Textbox(label="File Name") - with gr.Row(): - # hiden items - img_path = gr.Textbox(dir_name, visible=False) - is_img2img_flag = gr.Checkbox(is_img2img, visible=False) - image_index = gr.Textbox(value=-1, visible=False) - set_index = gr.Button('set_index', elem_id=id_name(is_img2img,"images_history_set_index")) - filenames = gr.State() - hide_image = gr.Image(visible=False, type="pil") - info1 = gr.Textbox(visible=False) - info2 = gr.Textbox(visible=False) + + # turn pages + gallery_inputs = [img_path, page_index, image_index, tabname_box] + gallery_outputs = [history_gallery, page_index, filenames, img_file_name, hide_image] - - # turn pages - gallery_inputs = [img_path, page_index, image_index] - gallery_outputs = [history_gallery, page_index, filenames, img_file_name, hide_image] - first_page.click(first_page_click, inputs=gallery_inputs, outputs=gallery_outputs) - next_page.click(next_page_click, inputs=gallery_inputs, outputs=gallery_outputs) - prev_page.click(prev_page_click, inputs=gallery_inputs, outputs=gallery_outputs) - end_page.click(end_page_click, inputs=gallery_inputs, outputs=gallery_outputs) - page_index.submit(page_index_change, inputs=gallery_inputs, outputs=gallery_outputs) - #page_index.change(page_index_change, inputs=[is_img2img_flag, img_path, page_index], outputs=[history_gallery, page_index]) + first_page.click(first_page_click, _js="images_history_turnpage", inputs=gallery_inputs, outputs=gallery_outputs) + next_page.click(next_page_click, _js="images_history_turnpage", inputs=gallery_inputs, outputs=gallery_outputs) + prev_page.click(prev_page_click, _js="images_history_turnpage", inputs=gallery_inputs, outputs=gallery_outputs) + end_page.click(end_page_click, _js="images_history_turnpage", inputs=gallery_inputs, outputs=gallery_outputs) + page_index.submit(page_index_change, _js="images_history_turnpage", inputs=gallery_inputs, outputs=gallery_outputs) + renew_page.click(page_index_change, _js="images_history_turnpage", inputs=gallery_inputs, outputs=gallery_outputs) + #page_index.change(page_index_change, inputs=[tabname_box, img_path, page_index], outputs=[history_gallery, page_index]) - #other funcitons - set_index.click(show_image_info, _js="images_history_get_current_img", inputs=[is_img2img_flag, img_path, filenames], outputs=[img_file_name, image_index, hide_image]) - delete.click(delete_image, inputs=[is_img2img_flag, img_path, img_file_name, page_index, filenames, image_index], outputs=gallery_outputs) - hide_image.change(fn=run_pnginfo, inputs=[hide_image], outputs=[info1, img_file_info, info2]) - switch_dict["fn"](pnginfo_send_to_txt2img, switch_dict["t2i"], img_file_info, 'switch_to_txt2img') - switch_dict["fn"](pnginfo_send_to_img2img, switch_dict["i2i"], img_file_info, 'switch_to_img2img_img2img') - - + #other funcitons + set_index.click(show_image_info, _js="images_history_get_current_img", inputs=[tabname_box, img_path, filenames], outputs=[img_file_name, image_index, hide_image]) + delete.click(delete_image,_js="images_history_delete", inputs=[tabname_box, img_path, img_file_name, page_index, filenames, image_index], outputs=[page_index, filenames]) + hide_image.change(fn=run_pnginfo, inputs=[hide_image], outputs=[info1, img_file_info, info2]) + switch_dict["fn"](pnginfo_send_to_txt2img, switch_dict["t2i"], img_file_info, 'switch_to_txt2img') + switch_dict["fn"](pnginfo_send_to_img2img, switch_dict["i2i"], img_file_info, 'switch_to_img2img_img2img') + + def create_history_tabs(gr, opts, run_pnginfo, switch_dict): - with gr.Blocks(analytics_enabled=False) as images_history: - with gr.Tabs() as tabs: - with gr.Tab("txt2img history", id="images_history_txt2img"): - with gr.Blocks(analytics_enabled=False) as images_history_txt2img: - show_images_history(gr, opts, False, run_pnginfo, switch_dict) - with gr.Tab("img2img history", id="images_history_img2img"): - with gr.Blocks(analytics_enabled=False) as images_history_img2img: - show_images_history(gr, opts, True, run_pnginfo, switch_dict) - return images_history + with gr.Blocks(analytics_enabled=False) as images_history: + with gr.Tabs() as tabs: + with gr.Tab("txt2img history"): + with gr.Blocks(analytics_enabled=False) as images_history_txt2img: + show_images_history(gr, opts, "txt2img", run_pnginfo, switch_dict) + with gr.Tab("img2img history"): + with gr.Blocks(analytics_enabled=False) as images_history_img2img: + show_images_history(gr, opts, "img2img", run_pnginfo, switch_dict) + with gr.Tab("extras history"): + with gr.Blocks(analytics_enabled=False) as images_history_img2img: + show_images_history(gr, opts, "extras", run_pnginfo, switch_dict) + return images_history diff --git a/style.css b/style.css index c0c3f2bb3..ca1cdba1c 100644 --- a/style.css +++ b/style.css @@ -463,3 +463,6 @@ input[type="range"]{ max-width: 32em; padding: 0; } +.images-history-hidden{ + display: none; +} \ No newline at end of file From 87d63bbab5c973ac5cec777ef7304d28f1ab3f24 Mon Sep 17 00:00:00 2001 From: yfszzx Date: Tue, 11 Oct 2022 20:37:03 +0800 Subject: [PATCH 04/11] images history improvement --- javascript/images_history.js | 6 ++---- modules/images_history.py | 30 +++++++++++++++--------------- 2 files changed, 17 insertions(+), 19 deletions(-) diff --git a/javascript/images_history.js b/javascript/images_history.js index 9a3e00a00..d62eb1814 100644 --- a/javascript/images_history.js +++ b/javascript/images_history.js @@ -93,7 +93,6 @@ function images_history_delete(tabname, img_path, img_file_name, page_index, fil buttons.push(e) } }) - img_num = buttons.length / 2 if (img_num == 1){ @@ -110,15 +109,14 @@ function images_history_delete(tabname, img_path, img_file_name, page_index, fil btn = buttons[image_index + 1] } setTimeout(function(btn){btn.click()}, 30, btn) - } - + } return [tabname, img_path, img_file_name, page_index, filenames, image_index] } function images_history_turnpage(img_path, page_index, image_index, tabname){ buttons = gradioApp().getElementById(tabname + '_images_history').querySelectorAll(".gallery-item") buttons.forEach(function(elem) { - elem.style.display = 'block' + elem.style.display = 'block' }) return [img_path, page_index, image_index, tabname] } diff --git a/modules/images_history.py b/modules/images_history.py index 01d11a01c..23f55b302 100644 --- a/modules/images_history.py +++ b/modules/images_history.py @@ -64,12 +64,12 @@ def show_images_history(gr, opts, tabname, run_pnginfo, switch_dict): elif tabname == "extras": dir_name = opts.outdir_extras_samples with gr.Row(): - renew_page = gr.Button('Renew', elem_id=tabname + "_images_history_renew_page") - first_page = gr.Button('First', elem_id=tabname + "_images_history_first_page") - prev_page = gr.Button('Prev') - page_index = gr.Number(value=1, label="Page Index") - next_page = gr.Button('Next', elem_id=tabname + "_images_history_next_page") - end_page = gr.Button('End') + renew_page = gr.Button('Renew', elem_id=tabname + "_images_history_renew_page") + first_page = gr.Button('First', elem_id=tabname + "_images_history_first_page") + prev_page = gr.Button('Prev') + page_index = gr.Number(value=1, label="Page Index") + next_page = gr.Button('Next', elem_id=tabname + "_images_history_next_page") + end_page = gr.Button('End') with gr.Row(elem_id=tabname + "_images_history"): with gr.Row(): with gr.Column(): @@ -84,15 +84,15 @@ def show_images_history(gr, opts, tabname, run_pnginfo, switch_dict): img_file_info = gr.Textbox(label="Generate Info") img_file_name = gr.Textbox(label="File Name") with gr.Row(): - # hiden items - img_path = gr.Textbox(dir_name, visible=False) - tabname_box = gr.Textbox(tabname, visible=False) - image_index = gr.Textbox(value=-1, visible=False) - set_index = gr.Button('set_index', elem_id=tabname + "_images_history_set_index", visible=False) - filenames = gr.State() - hide_image = gr.Image(visible=False, type="pil") - info1 = gr.Textbox(visible=False) - info2 = gr.Textbox(visible=False) + # hiden items + img_path = gr.Textbox(dir_name, visible=False) + tabname_box = gr.Textbox(tabname, visible=False) + image_index = gr.Textbox(value=-1, visible=False) + set_index = gr.Button('set_index', elem_id=tabname + "_images_history_set_index", visible=False) + filenames = gr.State() + hide_image = gr.Image(visible=False, type="pil") + info1 = gr.Textbox(visible=False) + info2 = gr.Textbox(visible=False) # turn pages From e05573e1adc1cde1e3bd7eb651a1ab27c446b3d5 Mon Sep 17 00:00:00 2001 From: yfszzx Date: Wed, 12 Oct 2022 20:47:55 +0800 Subject: [PATCH 05/11] images history improvement --- .gitignore | 1 + javascript/images_history.js | 224 +++++++++++++++++++++++------------ modules/images_history.py | 67 +++++++---- 3 files changed, 191 insertions(+), 101 deletions(-) diff --git a/.gitignore b/.gitignore index 7afc93953..434e23ce1 100644 --- a/.gitignore +++ b/.gitignore @@ -26,3 +26,4 @@ __pycache__ notification.mp3 /SwinIR /textual_inversion +/images_history_testui.py diff --git a/javascript/images_history.js b/javascript/images_history.js index d62eb1814..c9a631664 100644 --- a/javascript/images_history.js +++ b/javascript/images_history.js @@ -1,122 +1,192 @@ -images_history_tab_list = ["txt2img", "img2img", "extras"] -function images_history_init(){ - if (gradioApp().getElementById('txt2img_images_history_first_page') == null) { - setTimeout(images_history_init, 500) - } else { - for (i in images_history_tab_list ){ - tab = images_history_tab_list[i] - gradioApp().getElementById(tab + '_images_history').classList.add("images_history_gallery") - gradioApp().getElementById(tab + '_images_history_set_index').classList.add("images_history_set_index") - - } - gradioApp().getElementById("txt2img_images_history_first_page").click() - } -} -setTimeout(images_history_init, 500) -var images_history_button_actions = function(){ +var images_history_click_image = function(){ if (!this.classList.contains("transform")){ - gallery = this.parentElement - while(!gallery.classList.contains("images_history_gallery")){gallery = gallery.parentElement} - buttons = gallery.querySelectorAll(".gallery-item") - i = 0 - hidden_list = [] + var gallery = images_history_get_parent_by_class(this, "images_history_cantainor"); + var buttons = gallery.querySelectorAll(".gallery-item"); + var i = 0; + var hidden_list = []; buttons.forEach(function(e){ if (e.style.display == "none"){ - hidden_list.push(i) + hidden_list.push(i); } - i += 1 + i += 1; }) if (hidden_list.length > 0){ - setTimeout(images_history_hide_buttons, 10, hidden_list, gallery) - } - + setTimeout(images_history_hide_buttons, 10, hidden_list, gallery); + } } - images_history_set_image_info(this) - + images_history_set_image_info(this); } -onUiUpdate(function(){ - for (i in images_history_tab_list ){ - tab = images_history_tab_list[i] - buttons = gradioApp().querySelectorAll('#' + tab + '_images_history .gallery-item') - buttons.forEach(function(bnt){ - bnt.addEventListener('click', images_history_button_actions, true) - }); + +var images_history_click_tab = function(){ + var tabs_box = gradioApp().getElementById("images_history_tab"); + if (!tabs_box.classList.contains(this.getAttribute("tabname"))) { + gradioApp().getElementById(this.getAttribute("tabname") + "_images_history_renew_page").click(); + tabs_box.classList.add(this.getAttribute("tabname")) + } +} + +var images_history_close_full_view = function(){ + var box = images_history_get_parent_by_class(this, "images_history_cantainor"); + box.querySelector(".images_history_del_button").setAttribute("disabled", "disabled"); +} + +function images_history_get_parent_by_class(item, class_name){ + var parent = item.parentElement; + while(!parent.classList.contains(class_name)){ + parent = parent.parentElement; } -}) + return parent; +} + +function images_history_get_parent_by_tagname(item, tagname){ + var parent = item.parentElement; + tagname = tagname.toUpperCase() + while(parent.tagName != tagname){ + console.log(parent.tagName, tagname) + parent = parent.parentElement; + } + return parent; +} function images_history_hide_buttons(hidden_list, gallery){ - buttons = gallery.querySelectorAll(".gallery-item") - num = 0 + var buttons = gallery.querySelectorAll(".gallery-item"); + var num = 0; buttons.forEach(function(e){ if (e.style.display == "none"){ - num += 1 + num += 1; } }) if (num == hidden_list.length){ - setTimeout(images_history_hide_buttons, 10, hidden_list, gallery) + setTimeout(images_history_hide_buttons, 10, hidden_list, gallery); } for( i in hidden_list){ - buttons[hidden_list[i]].style.display = "none" + buttons[hidden_list[i]].style.display = "none"; } } function images_history_set_image_info(button){ - item = button.parentElement - while(item.tagName != "DIV"){item = item.parentElement} - buttons = item.querySelectorAll(".gallery-item") - index = -1 - i = 0 + var buttons = images_history_get_parent_by_tagname(button, "DIV").querySelectorAll(".gallery-item"); + var index = -1; + var i = 0; buttons.forEach(function(e){ - if(e==button){index = i} + if(e == button){ + index = i; + } if(e.style.display != "none"){ - i += 1 + i += 1; } }) - gallery = button.parentElement - while(!gallery.classList.contains("images_history_gallery")){gallery = gallery.parentElement} - set_btn = gallery.querySelector(".images_history_set_index") - set_btn.setAttribute("img_index", index) - set_btn.click() + var gallery = images_history_get_parent_by_class(button, "images_history_cantainor"); + var set_btn = gallery.querySelector(".images_history_set_index"); + set_btn.setAttribute("img_index", index); + set_btn.click(); + gradioApp().querySelectorAll(".images_history_del_button").forEach(function(btn){ + btn.setAttribute('disabled','disabled'); + }) + } function images_history_get_current_img(tabname, image_path, files){ - s = gradioApp().getElementById(tabname + '_images_history_set_index').getAttribute("img_index") - return [s, image_path, files] + return [ + gradioApp().getElementById(tabname + '_images_history_set_index').getAttribute("img_index"), + image_path, + files + ]; } function images_history_delete(tabname, img_path, img_file_name, page_index, filenames, image_index){ - image_index = parseInt(image_index) - tab = gradioApp().getElementById(tabname + '_images_history') - set_btn = tab.querySelector(".images_history_set_index") - buttons = [] + image_index = parseInt(image_index); + var tab = gradioApp().getElementById(tabname + '_images_history'); + var set_btn = tab.querySelector(".images_history_set_index"); + var buttons = []; tab.querySelectorAll(".gallery-item").forEach(function(e){ if (e.style.display != 'none'){ - buttons.push(e) + buttons.push(e); } - }) + }); - img_num = buttons.length / 2 - if (img_num == 1){ - setTimeout(function(tabname){ - gradioApp().getElementById(tabname + '_images_history_renew_page').click() - }, 30, tabname) + var img_num = buttons.length / 2; + if (img_num === 1){ + setTimeout(function(tabname){ + gradioApp().getElementById(tabname + '_images_history_renew_page').click(); + }, 30, tabname); } else { - buttons[image_index].style.display = 'none' - buttons[image_index + img_num].style.display = 'none' - if (image_index >= img_num - 1){ - console.log(buttons.length, img_num) - btn = buttons[img_num - 2] + buttons[image_index].style.display = 'none'; + buttons[image_index + img_num].style.display = 'none'; + var bnt; + if (image_index >= img_num - 1){ + btn = buttons[img_num - 2]; } else { - btn = buttons[image_index + 1] + btn = buttons[image_index + 1] ; } - setTimeout(function(btn){btn.click()}, 30, btn) + setTimeout(function(btn){btn.click()}, 30, btn); } - return [tabname, img_path, img_file_name, page_index, filenames, image_index] + return [tabname, img_path, img_file_name, page_index, filenames, image_index]; } function images_history_turnpage(img_path, page_index, image_index, tabname){ - buttons = gradioApp().getElementById(tabname + '_images_history').querySelectorAll(".gallery-item") + var buttons = gradioApp().getElementById(tabname + '_images_history').querySelectorAll(".gallery-item"); buttons.forEach(function(elem) { - elem.style.display = 'block' + elem.style.display = 'block'; }) - return [img_path, page_index, image_index, tabname] + return [img_path, page_index, image_index, tabname]; } + +function images_history_enable_del_buttons(){ + gradioApp().querySelectorAll(".images_history_del_button").forEach(function(btn){ + btn.removeAttribute('disabled'); + }) +} + +function images_history_init(){ + if (gradioApp().getElementById('txt2img_images_history_renew_page') == null) { + setTimeout(images_history_init, 500); + } else { + for (var i in images_history_tab_list ){ + tab = images_history_tab_list[i]; + gradioApp().getElementById(tab + '_images_history').classList.add("images_history_cantainor"); + gradioApp().getElementById(tab + '_images_history_set_index').classList.add("images_history_set_index"); + gradioApp().getElementById(tab + '_images_history_del_button').classList.add("images_history_del_button"); + gradioApp().getElementById(tab + '_images_history_gallery').classList.add("images_history_gallery"); + + + } + var tabs_box = gradioApp().getElementById("tab_images_history").querySelector("div").querySelector("div").querySelector("div"); + tabs_box.setAttribute("id", "images_history_tab"); + tabs_box.classList.add(images_history_tab_list[0]); + gradioApp().getElementById("txt2img_images_history_renew_page").click(); + } +} + +var images_history_tab_list = ["txt2img", "img2img", "extras"]; +var images_history_start_flag = false; + +onUiUpdate(function(){ + var tab = gradioApp().getElementById("images_history_tab"); + if (tab) { + if (!images_history_start_flag){ + images_history_init(); + images_history_start_flag = true; + } + var tab_btns = gradioApp().getElementById("images_history_tab").querySelectorAll("button"); + for (var i in images_history_tab_list ){ + var buttons = gradioApp().querySelectorAll('#' + images_history_tab_list[i] + '_images_history .gallery-item'); + buttons.forEach(function(bnt){ + bnt.addEventListener('click', images_history_click_image, true); + }); + var tabname = images_history_tab_list[i] + tab_btns[i].setAttribute("tabname", tabname); + tab_btns[i].addEventListener('click', images_history_click_tab, true); + // var cls_btn = gradioApp().getElementById(tabname + '_images_history_gallery').querySelector("svg"); + // if (cls_btn){ + // cls_btn.addEventListener('click', images_history_close_full_view, false); + // } + // console.log(cls_btn, cls_btn.parentElement.parentElement) + // if (cls_btn) { + // cls_btn = images_history_get_parent_by_tagname(cls_btn, "BUTTON"); + // cls_btn.addEventListener('click', images_history_close_full_view, true); + // } + } + + } +}); + diff --git a/modules/images_history.py b/modules/images_history.py index 23f55b302..77f692fe5 100644 --- a/modules/images_history.py +++ b/modules/images_history.py @@ -1,15 +1,29 @@ import os -def get_recent_images(dir_name, page_index, step, image_index): - #print(image_index) +import shutil +def get_recent_images(dir_name, page_index, step, image_index, tabname): + print(f"renew page {page_index}") page_index = int(page_index) f_list = os.listdir(dir_name) file_list = [] for file in f_list: if file[-4:] == ".txt": continue - file_list.append(file) + #subdirectories + if file[-10:].rfind(".") < 0: + sub_dir = os.path.join(dir_name, file) + if os.path.isfile(sub_dir): + continue + sub_file_list = os.listdir(sub_dir) + for sub_file in sub_file_list: + if sub_file[-4:] == ".txt": + continue + if os.path.isfile(os.path.join(sub_dir, sub_file) ): + file_list.append(os.path.join(file, sub_file)) + continue + file_list.append(file) + file_list = sorted(file_list, key=lambda file: -os.path.getctime(os.path.join(dir_name, file))) - num = 48 + num = 48 if tabname != "extras" else 12 max_page_index = len(file_list) // num + 1 page_index = max_page_index if page_index == -1 else page_index + step page_index = 1 if page_index < 1 else page_index @@ -26,26 +40,28 @@ def get_recent_images(dir_name, page_index, step, image_index): hide_image = os.path.join(dir_name, current_file) return [os.path.join(dir_name, file) for file in file_list], page_index, file_list, current_file, hide_image def first_page_click(dir_name, page_index, image_index, tabname): - return get_recent_images(dir_name, 1, 0, image_index) + return get_recent_images(dir_name, 1, 0, image_index, tabname) def end_page_click(dir_name, page_index, image_index, tabname): - return get_recent_images(dir_name, -1, 0, image_index) + return get_recent_images(dir_name, -1, 0, image_index, tabname) def prev_page_click(dir_name, page_index, image_index, tabname): - return get_recent_images(dir_name, page_index, -1, image_index) + return get_recent_images(dir_name, page_index, -1, image_index, tabname) def next_page_click(dir_name, page_index, image_index, tabname): - return get_recent_images(dir_name, page_index, 1, image_index) + return get_recent_images(dir_name, page_index, 1, image_index, tabname) def page_index_change(dir_name, page_index, image_index, tabname): - return get_recent_images(dir_name, page_index, 0, image_index) + return get_recent_images(dir_name, page_index, 0, image_index, tabname) def show_image_info(num, image_path, filenames): - #print("set img",num) + print(f"select image {num}") file = filenames[int(num)] return file, num, os.path.join(image_path, file) def delete_image(tabname, dir_name, name, page_index, filenames, image_index): - #print("filename", name) path = os.path.join(dir_name, name) - if os.path.exists(path): + if os.path.exists(path): print(f"Delete file {path}") - os.remove(path) + os.remove(path) + txt_file = os.path.splitext(path)[0] + ".txt" + if os.path.exists(txt_file): + os.remove(txt_file) new_file_list = [] for f in filenames: if f == name: @@ -64,25 +80,26 @@ def show_images_history(gr, opts, tabname, run_pnginfo, switch_dict): elif tabname == "extras": dir_name = opts.outdir_extras_samples with gr.Row(): - renew_page = gr.Button('Renew', elem_id=tabname + "_images_history_renew_page") - first_page = gr.Button('First', elem_id=tabname + "_images_history_first_page") - prev_page = gr.Button('Prev') + renew_page = gr.Button('Renew Page', elem_id=tabname + "_images_history_renew_page") + first_page = gr.Button('First Page') + prev_page = gr.Button('Prev Page') page_index = gr.Number(value=1, label="Page Index") - next_page = gr.Button('Next', elem_id=tabname + "_images_history_next_page") - end_page = gr.Button('End') + next_page = gr.Button('Next Page') + end_page = gr.Button('End Page') with gr.Row(elem_id=tabname + "_images_history"): with gr.Row(): - with gr.Column(): - history_gallery = gr.Gallery(show_label=False).style(grid=6) + with gr.Column(scale=2): + history_gallery = gr.Gallery(show_label=False, elem_id=tabname + "_images_history_gallery").style(grid=6) + delete = gr.Button('Delete', elem_id=tabname + "_images_history_del_button") with gr.Column(): with gr.Row(): - delete = gr.Button('Delete') + #pnginfo = gr.Button('PNG info') pnginfo_send_to_txt2img = gr.Button('Send to txt2img') pnginfo_send_to_img2img = gr.Button('Send to img2img') with gr.Row(): with gr.Column(): - img_file_info = gr.Textbox(label="Generate Info") - img_file_name = gr.Textbox(label="File Name") + img_file_info = gr.Textbox(label="Generate Info", interactive=False) + img_file_name = gr.Textbox(label="File Name", interactive=False) with gr.Row(): # hiden items img_path = gr.Textbox(dir_name, visible=False) @@ -90,7 +107,7 @@ def show_images_history(gr, opts, tabname, run_pnginfo, switch_dict): image_index = gr.Textbox(value=-1, visible=False) set_index = gr.Button('set_index', elem_id=tabname + "_images_history_set_index", visible=False) filenames = gr.State() - hide_image = gr.Image(visible=False, type="pil") + hide_image = gr.Image(type="pil", visible=False) info1 = gr.Textbox(visible=False) info2 = gr.Textbox(visible=False) @@ -111,6 +128,8 @@ def show_images_history(gr, opts, tabname, run_pnginfo, switch_dict): set_index.click(show_image_info, _js="images_history_get_current_img", inputs=[tabname_box, img_path, filenames], outputs=[img_file_name, image_index, hide_image]) delete.click(delete_image,_js="images_history_delete", inputs=[tabname_box, img_path, img_file_name, page_index, filenames, image_index], outputs=[page_index, filenames]) hide_image.change(fn=run_pnginfo, inputs=[hide_image], outputs=[info1, img_file_info, info2]) + hide_image.change(fn=None, _js="images_history_enable_del_buttons", inputs=None, outputs=None) + #pnginfo.click(fn=run_pnginfo, inputs=[hide_image], outputs=[info1, img_file_info, info2]) switch_dict["fn"](pnginfo_send_to_txt2img, switch_dict["t2i"], img_file_info, 'switch_to_txt2img') switch_dict["fn"](pnginfo_send_to_img2img, switch_dict["i2i"], img_file_info, 'switch_to_img2img_img2img') From a1a94b8b5f342f467aecc53b21b80ed0227ee76a Mon Sep 17 00:00:00 2001 From: yfszzx Date: Thu, 13 Oct 2022 00:19:34 +0800 Subject: [PATCH 06/11] images history improvement --- javascript/images_history.js | 125 ++++++++++++++++++----------------- modules/images_history.py | 7 +- modules/ui.py | 40 ++++++----- 3 files changed, 88 insertions(+), 84 deletions(-) diff --git a/javascript/images_history.js b/javascript/images_history.js index c9a631664..620f242c3 100644 --- a/javascript/images_history.js +++ b/javascript/images_history.js @@ -18,20 +18,26 @@ var images_history_click_image = function(){ } var images_history_click_tab = function(){ - var tabs_box = gradioApp().getElementById("images_history_tab"); - if (!tabs_box.classList.contains(this.getAttribute("tabname"))) { - gradioApp().getElementById(this.getAttribute("tabname") + "_images_history_renew_page").click(); - tabs_box.classList.add(this.getAttribute("tabname")) - } + var tabs_box = gradioApp().getElementById("images_history_tab"); + if (!tabs_box.classList.contains(this.getAttribute("tabname"))) { + gradioApp().getElementById(this.getAttribute("tabname") + "_images_history_renew_page").click(); + tabs_box.classList.add(this.getAttribute("tabname")) + } } var images_history_close_full_view = function(){ - var box = images_history_get_parent_by_class(this, "images_history_cantainor"); - box.querySelector(".images_history_del_button").setAttribute("disabled", "disabled"); + var box = images_history_get_parent_by_class(this, "images_history_cantainor"); + box.querySelector(".images_history_del_button").setAttribute("disabled", "disabled"); +} + +function images_history_disabled_del(){ + gradioApp().querySelectorAll(".images_history_del_button").forEach(function(btn){ + btn.setAttribute('disabled','disabled'); + }); } function images_history_get_parent_by_class(item, class_name){ - var parent = item.parentElement; + var parent = item.parentElement; while(!parent.classList.contains(class_name)){ parent = parent.parentElement; } @@ -39,14 +45,15 @@ function images_history_get_parent_by_class(item, class_name){ } function images_history_get_parent_by_tagname(item, tagname){ - var parent = item.parentElement; - tagname = tagname.toUpperCase() + var parent = item.parentElement; + tagname = tagname.toUpperCase() while(parent.tagName != tagname){ - console.log(parent.tagName, tagname) + console.log(parent.tagName, tagname) parent = parent.parentElement; } return parent; } + function images_history_hide_buttons(hidden_list, gallery){ var buttons = gallery.querySelectorAll(".gallery-item"); var num = 0; @@ -54,7 +61,7 @@ function images_history_hide_buttons(hidden_list, gallery){ if (e.style.display == "none"){ num += 1; } - }) + }); if (num == hidden_list.length){ setTimeout(images_history_hide_buttons, 10, hidden_list, gallery); } @@ -74,14 +81,15 @@ function images_history_set_image_info(button){ if(e.style.display != "none"){ i += 1; } - }) + }); var gallery = images_history_get_parent_by_class(button, "images_history_cantainor"); var set_btn = gallery.querySelector(".images_history_set_index"); - set_btn.setAttribute("img_index", index); + var curr_idx = set_btn.getAttribute("img_index", index); + if (curr_idx != index) { + set_btn.setAttribute("img_index", index); + images_history_disabled_del(); + } set_btn.click(); - gradioApp().querySelectorAll(".images_history_del_button").forEach(function(btn){ - btn.setAttribute('disabled','disabled'); - }) } @@ -102,24 +110,24 @@ function images_history_delete(tabname, img_path, img_file_name, page_index, fil if (e.style.display != 'none'){ buttons.push(e); } - }); - + }); var img_num = buttons.length / 2; if (img_num === 1){ setTimeout(function(tabname){ gradioApp().getElementById(tabname + '_images_history_renew_page').click(); }, 30, tabname); - } else { + } else { buttons[image_index].style.display = 'none'; buttons[image_index + img_num].style.display = 'none'; var bnt; if (image_index >= img_num - 1){ btn = buttons[img_num - 2]; - } else { + } else { btn = buttons[image_index + 1] ; - } + } setTimeout(function(btn){btn.click()}, 30, btn); - } + } + images_history_disabled_del(); return [tabname, img_path, img_file_name, page_index, filenames, image_index]; } @@ -132,61 +140,58 @@ function images_history_turnpage(img_path, page_index, image_index, tabname){ } function images_history_enable_del_buttons(){ - gradioApp().querySelectorAll(".images_history_del_button").forEach(function(btn){ - btn.removeAttribute('disabled'); + gradioApp().querySelectorAll(".images_history_del_button").forEach(function(btn){ + btn.removeAttribute('disabled'); }) } function images_history_init(){ - if (gradioApp().getElementById('txt2img_images_history_renew_page') == null) { - setTimeout(images_history_init, 500); - } else { + var load_txt2img_button = gradioApp().getElementById('txt2img_images_history_renew_page') + if (load_txt2img_button){ for (var i in images_history_tab_list ){ tab = images_history_tab_list[i]; gradioApp().getElementById(tab + '_images_history').classList.add("images_history_cantainor"); gradioApp().getElementById(tab + '_images_history_set_index').classList.add("images_history_set_index"); gradioApp().getElementById(tab + '_images_history_del_button').classList.add("images_history_del_button"); - gradioApp().getElementById(tab + '_images_history_gallery').classList.add("images_history_gallery"); - - + gradioApp().getElementById(tab + '_images_history_gallery').classList.add("images_history_gallery"); + } var tabs_box = gradioApp().getElementById("tab_images_history").querySelector("div").querySelector("div").querySelector("div"); - tabs_box.setAttribute("id", "images_history_tab"); - tabs_box.classList.add(images_history_tab_list[0]); - gradioApp().getElementById("txt2img_images_history_renew_page").click(); - } + tabs_box.setAttribute("id", "images_history_tab"); + var tab_btns = tabs_box.querySelectorAll("button"); + for (var i in images_history_tab_list){ + var tabname = images_history_tab_list[i] + tab_btns[i].setAttribute("tabname", tabname); + tab_btns[i].addEventListener('click', images_history_click_tab); + } + tabs_box.classList.add(images_history_tab_list[0]); + load_txt2img_button.click(); + } else { + setTimeout(images_history_init, 500); + } } var images_history_tab_list = ["txt2img", "img2img", "extras"]; -var images_history_start_flag = false; - -onUiUpdate(function(){ - var tab = gradioApp().getElementById("images_history_tab"); - if (tab) { - if (!images_history_start_flag){ - images_history_init(); - images_history_start_flag = true; - } - var tab_btns = gradioApp().getElementById("images_history_tab").querySelectorAll("button"); - for (var i in images_history_tab_list ){ - var buttons = gradioApp().querySelectorAll('#' + images_history_tab_list[i] + '_images_history .gallery-item'); - buttons.forEach(function(bnt){ - bnt.addEventListener('click', images_history_click_image, true); - }); - var tabname = images_history_tab_list[i] - tab_btns[i].setAttribute("tabname", tabname); - tab_btns[i].addEventListener('click', images_history_click_tab, true); +setTimeout(images_history_init, 500) +document.addEventListener("DOMContentLoaded", function() { + var mutationObserver = new MutationObserver(function(m){ + for (var i in images_history_tab_list ){ + var buttons = gradioApp().querySelectorAll('#' + images_history_tab_list[i] + '_images_history .gallery-item'); + buttons.forEach(function(bnt){ + bnt.addEventListener('click', images_history_click_image, true); + }); // var cls_btn = gradioApp().getElementById(tabname + '_images_history_gallery').querySelector("svg"); // if (cls_btn){ - // cls_btn.addEventListener('click', images_history_close_full_view, false); + // cls_btn.addEventListener('click', images_history_close_full_view, false); // } // console.log(cls_btn, cls_btn.parentElement.parentElement) // if (cls_btn) { - // cls_btn = images_history_get_parent_by_tagname(cls_btn, "BUTTON"); - // cls_btn.addEventListener('click', images_history_close_full_view, true); - // } - } + // cls_btn = images_history_get_parent_by_tagname(cls_btn, "BUTTON"); + // cls_btn.addEventListener('click', images_history_close_full_view, true); + } + }); + mutationObserver.observe( gradioApp(), { childList:true, subtree:true }); + +}); - } -}); diff --git a/modules/images_history.py b/modules/images_history.py index 2bc4b7eee..1bca0ad92 100644 --- a/modules/images_history.py +++ b/modules/images_history.py @@ -61,7 +61,7 @@ def delete_image(tabname, dir_name, name, page_index, filenames, image_index): os.remove(path) txt_file = os.path.splitext(path)[0] + ".txt" if os.path.exists(txt_file): - os.remove(txt_file) + os.remove(txt_file) new_file_list = [] for f in filenames: if f == name: @@ -88,7 +88,7 @@ def show_images_history(gr, opts, tabname, run_pnginfo, switch_dict): end_page = gr.Button('End Page') with gr.Row(elem_id=tabname + "_images_history"): with gr.Row(): - with gr.Column(scale=2): + with gr.Column(scale=2): history_gallery = gr.Gallery(show_label=False, elem_id=tabname + "_images_history_gallery").style(grid=6) delete = gr.Button('Delete', elem_id=tabname + "_images_history_del_button") with gr.Column(): @@ -126,9 +126,10 @@ def show_images_history(gr, opts, tabname, run_pnginfo, switch_dict): #other funcitons set_index.click(show_image_info, _js="images_history_get_current_img", inputs=[tabname_box, img_path, filenames], outputs=[img_file_name, image_index, hide_image]) + img_file_name.change(fn=None, _js="images_history_enable_del_buttons", inputs=None, outputs=None) delete.click(delete_image,_js="images_history_delete", inputs=[tabname_box, img_path, img_file_name, page_index, filenames, image_index], outputs=[page_index, filenames]) hide_image.change(fn=run_pnginfo, inputs=[hide_image], outputs=[info1, img_file_info, info2]) - hide_image.change(fn=None, _js="images_history_enable_del_buttons", inputs=None, outputs=None) + #pnginfo.click(fn=run_pnginfo, inputs=[hide_image], outputs=[info1, img_file_info, info2]) switch_dict["fn"](pnginfo_send_to_txt2img, switch_dict["t2i"], img_file_info, 'switch_to_txt2img') switch_dict["fn"](pnginfo_send_to_img2img, switch_dict["i2i"], img_file_info, 'switch_to_img2img_img2img') diff --git a/modules/ui.py b/modules/ui.py index 94297ba65..8cd12b518 100644 --- a/modules/ui.py +++ b/modules/ui.py @@ -39,7 +39,7 @@ import modules.generation_parameters_copypaste from modules import prompt_parser from modules.images import save_image import modules.textual_inversion.ui -import modules.hypernetwork.ui +import modules.hypernetworks.ui import modules.images_history as img_his # this is a fix for Windows users. Without it, javascript files will be served with text/html content-type and the browser will not show any UI @@ -554,6 +554,7 @@ def create_ui(wrap_gradio_gpu_call): custom_inputs = modules.scripts.scripts_txt2img.setup_ui(is_img2img=False) with gr.Column(variant='panel'): + with gr.Group(): txt2img_preview = gr.Image(elem_id='txt2img_preview', visible=False) txt2img_gallery = gr.Gallery(label='Output', show_label=False, elem_id='txt2img_gallery').style(grid=4) @@ -573,9 +574,9 @@ def create_ui(wrap_gradio_gpu_call): with gr.Row(): download_files = gr.File(None, file_count="multiple", interactive=False, show_label=False, visible=False) - with gr.Group(): - html_info = gr.HTML() - generation_info = gr.Textbox(visible=False) + with gr.Group(): + html_info = gr.HTML() + generation_info = gr.Textbox(visible=False) connect_reuse_seed(seed, reuse_seed, generation_info, dummy_component, is_subseed=False) connect_reuse_seed(subseed, reuse_subseed, generation_info, dummy_component, is_subseed=True) @@ -669,7 +670,6 @@ def create_ui(wrap_gradio_gpu_call): ] modules.generation_parameters_copypaste.connect_paste(paste, txt2img_paste_fields, txt2img_prompt) token_button.click(fn=update_token_counter, inputs=[txt2img_prompt, steps], outputs=[token_counter]) - with gr.Blocks(analytics_enabled=False) as img2img_interface: img2img_prompt, roll, img2img_prompt_style, img2img_negative_prompt, img2img_prompt_style2, submit, img2img_interrogate, img2img_deepbooru, img2img_prompt_style_apply, img2img_save_style, paste, token_counter, token_button = create_toprow(is_img2img=True) @@ -762,10 +762,10 @@ def create_ui(wrap_gradio_gpu_call): with gr.Row(): download_files = gr.File(None, file_count="multiple", interactive=False, show_label=False, visible=False) - with gr.Group(): - html_info = gr.HTML() - generation_info = gr.Textbox(visible=False) - + with gr.Group(): + html_info = gr.HTML() + generation_info = gr.Textbox(visible=False) + connect_reuse_seed(seed, reuse_seed, generation_info, dummy_component, is_subseed=False) connect_reuse_seed(subseed, reuse_subseed, generation_info, dummy_component, is_subseed=True) @@ -1016,6 +1016,13 @@ def create_ui(wrap_gradio_gpu_call): inputs=[image], outputs=[html, generation_info, html2], ) + #images history + images_history_switch_dict = { + "fn":modules.generation_parameters_copypaste.connect_paste, + "t2i":txt2img_paste_fields, + "i2i":img2img_paste_fields + } + images_history = img_his.create_history_tabs(gr, opts, wrap_gradio_call(modules.extras.run_pnginfo), images_history_switch_dict) with gr.Blocks() as modelmerger_interface: with gr.Row().style(equal_height=False): @@ -1285,16 +1292,7 @@ Requested path was: {f} opts.save(shared.config_filename) - return f'{changed} settings changed.', opts.dumpjson() - - #images history - images_history_switch_dict = { - "fn":modules.generation_parameters_copypaste.connect_paste, - "t2i":txt2img_paste_fields, - "i2i":img2img_paste_fields - } - images_history = img_his.create_history_tabs(gr, opts, wrap_gradio_call(modules.extras.run_pnginfo), images_history_switch_dict) - + return f'{changed} settings changed.', opts.dumpjson() def run_settings_single(value, key): if not opts.same_type(value, opts.data_labels[key].default): @@ -1393,11 +1391,10 @@ Requested path was: {f} (img2img_interface, "img2img", "img2img"), (extras_interface, "Extras", "extras"), (pnginfo_interface, "PNG Info", "pnginfo"), - (modelmerger_interface, "Checkpoint Merger", "modelmerger"), (images_history, "History", "images_history"), + (modelmerger_interface, "Checkpoint Merger", "modelmerger"), (train_interface, "Train", "ti"), (settings_interface, "Settings", "settings"), - ] with open(os.path.join(script_path, "style.css"), "r", encoding="utf8") as file: @@ -1616,3 +1613,4 @@ if 'gradio_routes_templates_response' not in globals(): gradio_routes_templates_response = gradio.routes.templates.TemplateResponse gradio.routes.templates.TemplateResponse = template_response + From a2aa2a68bc7868320b502a78765be597e507ce45 Mon Sep 17 00:00:00 2001 From: yfszzx Date: Thu, 13 Oct 2022 00:21:16 +0800 Subject: [PATCH 07/11] images history improvement --- modules/images_history.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/images_history.py b/modules/images_history.py index 1bca0ad92..6408973c6 100644 --- a/modules/images_history.py +++ b/modules/images_history.py @@ -1,7 +1,7 @@ import os import shutil def get_recent_images(dir_name, page_index, step, image_index, tabname): - print(f"renew page {page_index}") + #print(f"renew page {page_index}") page_index = int(page_index) f_list = os.listdir(dir_name) file_list = [] @@ -51,7 +51,7 @@ def page_index_change(dir_name, page_index, image_index, tabname): return get_recent_images(dir_name, page_index, 0, image_index, tabname) def show_image_info(num, image_path, filenames): - print(f"select image {num}") + #print(f"select image {num}") file = filenames[int(num)] return file, num, os.path.join(image_path, file) def delete_image(tabname, dir_name, name, page_index, filenames, image_index): From 717ba4c71c86cb2d49d731caeed82ce8bec0c057 Mon Sep 17 00:00:00 2001 From: yfszzx Date: Thu, 13 Oct 2022 00:27:45 +0800 Subject: [PATCH 08/11] images history improvement --- javascript/images_history.js | 2 +- style.css | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/javascript/images_history.js b/javascript/images_history.js index 620f242c3..c5c2886ef 100644 --- a/javascript/images_history.js +++ b/javascript/images_history.js @@ -172,7 +172,7 @@ function images_history_init(){ } var images_history_tab_list = ["txt2img", "img2img", "extras"]; -setTimeout(images_history_init, 500) +setTimeout(images_history_init, 500); document.addEventListener("DOMContentLoaded", function() { var mutationObserver = new MutationObserver(function(m){ for (var i in images_history_tab_list ){ diff --git a/style.css b/style.css index 7704e7bd1..c75dce4c6 100644 --- a/style.css +++ b/style.css @@ -20,7 +20,7 @@ padding-right: 0.25em; margin: 0.1em 0; opacity: 0%; - cursor: default; + cursor: default; } .output-html p {margin: 0 0.5em;} @@ -442,7 +442,7 @@ input[type="range"]{ } .red { - color: red; + color: red; } .gallery-item { From 716a9e034f1aff434083363b218bd6043a774fc2 Mon Sep 17 00:00:00 2001 From: yfszzx Date: Thu, 13 Oct 2022 12:19:50 +0800 Subject: [PATCH 09/11] images history delete a number of images consecutively next --- javascript/images_history.js | 24 ++++++++++++-------- modules/images_history.py | 44 ++++++++++++++++++++---------------- 2 files changed, 39 insertions(+), 29 deletions(-) diff --git a/javascript/images_history.js b/javascript/images_history.js index c5c2886ef..8fa4a15e3 100644 --- a/javascript/images_history.js +++ b/javascript/images_history.js @@ -101,7 +101,7 @@ function images_history_get_current_img(tabname, image_path, files){ ]; } -function images_history_delete(tabname, img_path, img_file_name, page_index, filenames, image_index){ +function images_history_delete(del_num, tabname, img_path, img_file_name, page_index, filenames, image_index){ image_index = parseInt(image_index); var tab = gradioApp().getElementById(tabname + '_images_history'); var set_btn = tab.querySelector(".images_history_set_index"); @@ -112,23 +112,29 @@ function images_history_delete(tabname, img_path, img_file_name, page_index, fil } }); var img_num = buttons.length / 2; - if (img_num === 1){ + if (img_num <= del_num){ setTimeout(function(tabname){ gradioApp().getElementById(tabname + '_images_history_renew_page').click(); }, 30, tabname); - } else { - buttons[image_index].style.display = 'none'; - buttons[image_index + img_num].style.display = 'none'; + } else { + var next_img + for (var i = 0; i < del_num; i++){ + if (image_index + i < image_index + img_num){ + buttons[image_index + i].style.display = 'none'; + buttons[image_index + img_num + 1].style.display = 'none'; + next_img = image_index + i + 1 + } + } var bnt; - if (image_index >= img_num - 1){ - btn = buttons[img_num - 2]; + if (next_img >= img_num){ + btn = buttons[image_index - del_num]; } else { - btn = buttons[image_index + 1] ; + btn = buttons[next_img]; } setTimeout(function(btn){btn.click()}, 30, btn); } images_history_disabled_del(); - return [tabname, img_path, img_file_name, page_index, filenames, image_index]; + return [del_num, tabname, img_path, img_file_name, page_index, filenames, image_index]; } function images_history_turnpage(img_path, page_index, image_index, tabname){ diff --git a/modules/images_history.py b/modules/images_history.py index 6408973c6..f812ea4e9 100644 --- a/modules/images_history.py +++ b/modules/images_history.py @@ -54,23 +54,26 @@ def show_image_info(num, image_path, filenames): #print(f"select image {num}") file = filenames[int(num)] return file, num, os.path.join(image_path, file) -def delete_image(tabname, dir_name, name, page_index, filenames, image_index): - path = os.path.join(dir_name, name) - if os.path.exists(path): - print(f"Delete file {path}") - os.remove(path) - txt_file = os.path.splitext(path)[0] + ".txt" - if os.path.exists(txt_file): - os.remove(txt_file) - new_file_list = [] - for f in filenames: - if f == name: - continue - new_file_list.append(f) - else: - print(f"Not exists file {path}") - new_file_list = filenames - return page_index, new_file_list +def delete_image(delete_num, tabname, dir_name, name, page_index, filenames, image_index): + delete_num = int(delete_num) + index = list(filenames).index(name) + i = 0 + new_file_list = [] + for name in filenames: + if i >= index and i < index + delete_num: + path = os.path.join(dir_name, name) + if os.path.exists(path): + print(f"Delete file {path}") + os.remove(path) + txt_file = os.path.splitext(path)[0] + ".txt" + if os.path.exists(txt_file): + os.remove(txt_file) + else: + print(f"Not exists file {path}") + else: + new_file_list.append(name) + i += 1 + return page_index, new_file_list, 1 def show_images_history(gr, opts, tabname, run_pnginfo, switch_dict): if tabname == "txt2img": @@ -90,10 +93,11 @@ def show_images_history(gr, opts, tabname, run_pnginfo, switch_dict): with gr.Row(): with gr.Column(scale=2): history_gallery = gr.Gallery(show_label=False, elem_id=tabname + "_images_history_gallery").style(grid=6) - delete = gr.Button('Delete', elem_id=tabname + "_images_history_del_button") + with gr.Row(): + delete = gr.Button('Delete', elem_id=tabname + "_images_history_del_button") + delete_num = gr.Number(value=1, interactive=True, label="number of images to delete consecutively next") with gr.Column(): with gr.Row(): - #pnginfo = gr.Button('PNG info') pnginfo_send_to_txt2img = gr.Button('Send to txt2img') pnginfo_send_to_img2img = gr.Button('Send to img2img') with gr.Row(): @@ -127,7 +131,7 @@ def show_images_history(gr, opts, tabname, run_pnginfo, switch_dict): #other funcitons set_index.click(show_image_info, _js="images_history_get_current_img", inputs=[tabname_box, img_path, filenames], outputs=[img_file_name, image_index, hide_image]) img_file_name.change(fn=None, _js="images_history_enable_del_buttons", inputs=None, outputs=None) - delete.click(delete_image,_js="images_history_delete", inputs=[tabname_box, img_path, img_file_name, page_index, filenames, image_index], outputs=[page_index, filenames]) + delete.click(delete_image,_js="images_history_delete", inputs=[delete_num, tabname_box, img_path, img_file_name, page_index, filenames, image_index], outputs=[page_index, filenames, delete_num]) hide_image.change(fn=run_pnginfo, inputs=[hide_image], outputs=[info1, img_file_info, info2]) #pnginfo.click(fn=run_pnginfo, inputs=[hide_image], outputs=[info1, img_file_info, info2]) From a1489f94283c07824a7a58353c03dc89541bbe49 Mon Sep 17 00:00:00 2001 From: yfszzx Date: Fri, 14 Oct 2022 07:13:38 +0800 Subject: [PATCH 10/11] images history fix all known bug --- .gitignore | 1 + javascript/images_history.js | 23 +++++++--------- modules/images_history.py | 51 +++++++++++++++++++----------------- repositorieslatent-diffusion | 1 - style.css | 6 ++--- 5 files changed, 40 insertions(+), 42 deletions(-) delete mode 160000 repositorieslatent-diffusion diff --git a/.gitignore b/.gitignore index 434e23ce1..b9e23112e 100644 --- a/.gitignore +++ b/.gitignore @@ -27,3 +27,4 @@ notification.mp3 /SwinIR /textual_inversion /images_history_testui.py +/repositorieslatent-diffusion diff --git a/javascript/images_history.js b/javascript/images_history.js index 8fa4a15e3..3a20056b9 100644 --- a/javascript/images_history.js +++ b/javascript/images_history.js @@ -25,11 +25,6 @@ var images_history_click_tab = function(){ } } -var images_history_close_full_view = function(){ - var box = images_history_get_parent_by_class(this, "images_history_cantainor"); - box.querySelector(".images_history_del_button").setAttribute("disabled", "disabled"); -} - function images_history_disabled_del(){ gradioApp().querySelectorAll(".images_history_del_button").forEach(function(btn){ btn.setAttribute('disabled','disabled'); @@ -182,18 +177,18 @@ setTimeout(images_history_init, 500); document.addEventListener("DOMContentLoaded", function() { var mutationObserver = new MutationObserver(function(m){ for (var i in images_history_tab_list ){ - var buttons = gradioApp().querySelectorAll('#' + images_history_tab_list[i] + '_images_history .gallery-item'); + let tabname = images_history_tab_list[i] + var buttons = gradioApp().querySelectorAll('#' + tabname + '_images_history .gallery-item'); buttons.forEach(function(bnt){ bnt.addEventListener('click', images_history_click_image, true); }); - // var cls_btn = gradioApp().getElementById(tabname + '_images_history_gallery').querySelector("svg"); - // if (cls_btn){ - // cls_btn.addEventListener('click', images_history_close_full_view, false); - // } - // console.log(cls_btn, cls_btn.parentElement.parentElement) - // if (cls_btn) { - // cls_btn = images_history_get_parent_by_tagname(cls_btn, "BUTTON"); - // cls_btn.addEventListener('click', images_history_close_full_view, true); + var cls_btn = gradioApp().getElementById(tabname + '_images_history_gallery').querySelector("svg"); + if (cls_btn){ + cls_btn.addEventListener('click', function(){ + gradioApp().getElementById(tabname + '_images_history_renew_page').click(); + }, false); + } + } }); mutationObserver.observe( gradioApp(), { childList:true, subtree:true }); diff --git a/modules/images_history.py b/modules/images_history.py index f812ea4e9..cdfcffed6 100644 --- a/modules/images_history.py +++ b/modules/images_history.py @@ -38,7 +38,7 @@ def get_recent_images(dir_name, page_index, step, image_index, tabname): else: current_file = file_list[int(image_index)] hide_image = os.path.join(dir_name, current_file) - return [os.path.join(dir_name, file) for file in file_list], page_index, file_list, current_file, hide_image + return [os.path.join(dir_name, file) for file in file_list], page_index, file_list, current_file, hide_image, "" def first_page_click(dir_name, page_index, image_index, tabname): return get_recent_images(dir_name, 1, 0, image_index, tabname) def end_page_click(dir_name, page_index, image_index, tabname): @@ -55,25 +55,28 @@ def show_image_info(num, image_path, filenames): file = filenames[int(num)] return file, num, os.path.join(image_path, file) def delete_image(delete_num, tabname, dir_name, name, page_index, filenames, image_index): - delete_num = int(delete_num) - index = list(filenames).index(name) - i = 0 - new_file_list = [] - for name in filenames: - if i >= index and i < index + delete_num: - path = os.path.join(dir_name, name) - if os.path.exists(path): - print(f"Delete file {path}") - os.remove(path) - txt_file = os.path.splitext(path)[0] + ".txt" - if os.path.exists(txt_file): - os.remove(txt_file) + if name == "": + return filenames, delete_num + else: + delete_num = int(delete_num) + index = list(filenames).index(name) + i = 0 + new_file_list = [] + for name in filenames: + if i >= index and i < index + delete_num: + path = os.path.join(dir_name, name) + if os.path.exists(path): + print(f"Delete file {path}") + os.remove(path) + txt_file = os.path.splitext(path)[0] + ".txt" + if os.path.exists(txt_file): + os.remove(txt_file) + else: + print(f"Not exists file {path}") else: - print(f"Not exists file {path}") - else: - new_file_list.append(name) - i += 1 - return page_index, new_file_list, 1 + new_file_list.append(name) + i += 1 + return new_file_list, 1 def show_images_history(gr, opts, tabname, run_pnginfo, switch_dict): if tabname == "txt2img": @@ -93,9 +96,9 @@ def show_images_history(gr, opts, tabname, run_pnginfo, switch_dict): with gr.Row(): with gr.Column(scale=2): history_gallery = gr.Gallery(show_label=False, elem_id=tabname + "_images_history_gallery").style(grid=6) - with gr.Row(): - delete = gr.Button('Delete', elem_id=tabname + "_images_history_del_button") - delete_num = gr.Number(value=1, interactive=True, label="number of images to delete consecutively next") + with gr.Row(): + delete_num = gr.Number(value=1, interactive=True, label="number of images to delete consecutively next") + delete = gr.Button('Delete', elem_id=tabname + "_images_history_del_button") with gr.Column(): with gr.Row(): pnginfo_send_to_txt2img = gr.Button('Send to txt2img') @@ -118,7 +121,7 @@ def show_images_history(gr, opts, tabname, run_pnginfo, switch_dict): # turn pages gallery_inputs = [img_path, page_index, image_index, tabname_box] - gallery_outputs = [history_gallery, page_index, filenames, img_file_name, hide_image] + gallery_outputs = [history_gallery, page_index, filenames, img_file_name, hide_image, img_file_name] first_page.click(first_page_click, _js="images_history_turnpage", inputs=gallery_inputs, outputs=gallery_outputs) next_page.click(next_page_click, _js="images_history_turnpage", inputs=gallery_inputs, outputs=gallery_outputs) @@ -131,7 +134,7 @@ def show_images_history(gr, opts, tabname, run_pnginfo, switch_dict): #other funcitons set_index.click(show_image_info, _js="images_history_get_current_img", inputs=[tabname_box, img_path, filenames], outputs=[img_file_name, image_index, hide_image]) img_file_name.change(fn=None, _js="images_history_enable_del_buttons", inputs=None, outputs=None) - delete.click(delete_image,_js="images_history_delete", inputs=[delete_num, tabname_box, img_path, img_file_name, page_index, filenames, image_index], outputs=[page_index, filenames, delete_num]) + delete.click(delete_image,_js="images_history_delete", inputs=[delete_num, tabname_box, img_path, img_file_name, page_index, filenames, image_index], outputs=[filenames, delete_num]) hide_image.change(fn=run_pnginfo, inputs=[hide_image], outputs=[info1, img_file_info, info2]) #pnginfo.click(fn=run_pnginfo, inputs=[hide_image], outputs=[info1, img_file_info, info2]) diff --git a/repositorieslatent-diffusion b/repositorieslatent-diffusion deleted file mode 160000 index abf33e700..000000000 --- a/repositorieslatent-diffusion +++ /dev/null @@ -1 +0,0 @@ -Subproject commit abf33e7002d59d9085081bce93ec798dcabd49af diff --git a/style.css b/style.css index c75dce4c6..e6fa10b4f 100644 --- a/style.css +++ b/style.css @@ -20,7 +20,7 @@ padding-right: 0.25em; margin: 0.1em 0; opacity: 0%; - cursor: default; + cursor: default; } .output-html p {margin: 0 0.5em;} @@ -442,7 +442,7 @@ input[type="range"]{ } .red { - color: red; + color: red; } .gallery-item { @@ -505,4 +505,4 @@ canvas[key="mask"] { top: -0.6em; z-index: 200; width: 8em; -} \ No newline at end of file +} From 4a37c7eedeab579efec03e8dae3f3f9fd4a37b02 Mon Sep 17 00:00:00 2001 From: yfszzx Date: Fri, 14 Oct 2022 11:48:28 +0800 Subject: [PATCH 11/11] fix deep nesting directories problem --- modules/images_history.py | 76 +++++++++++++++++++++------------------ 1 file changed, 42 insertions(+), 34 deletions(-) diff --git a/modules/images_history.py b/modules/images_history.py index cdfcffed6..723f5301c 100644 --- a/modules/images_history.py +++ b/modules/images_history.py @@ -1,44 +1,47 @@ import os import shutil +def traverse_all_files(output_dir, image_list, curr_dir=None): + curr_path = output_dir if curr_dir is None else os.path.join(output_dir, curr_dir) + try: + f_list = os.listdir(curr_path) + except: + if curr_dir[-10:].rfind(".") > 0 and curr_dir[-4:] != ".txt": + image_list.append(curr_dir) + return image_list + for file in f_list: + file = file if curr_dir is None else os.path.join(curr_dir, file) + file_path = os.path.join(curr_path, file) + if file[-4:] == ".txt": + pass + elif os.path.isfile(file_path) and file[-10:].rfind(".") > 0: + image_list.append(file) + else: + image_list = traverse_all_files(output_dir, image_list, file) + return image_list + + def get_recent_images(dir_name, page_index, step, image_index, tabname): - #print(f"renew page {page_index}") page_index = int(page_index) f_list = os.listdir(dir_name) - file_list = [] - for file in f_list: - if file[-4:] == ".txt": - continue - #subdirectories - if file[-10:].rfind(".") < 0: - sub_dir = os.path.join(dir_name, file) - if os.path.isfile(sub_dir): - continue - sub_file_list = os.listdir(sub_dir) - for sub_file in sub_file_list: - if sub_file[-4:] == ".txt": - continue - if os.path.isfile(os.path.join(sub_dir, sub_file) ): - file_list.append(os.path.join(file, sub_file)) - continue - file_list.append(file) - - file_list = sorted(file_list, key=lambda file: -os.path.getctime(os.path.join(dir_name, file))) + image_list = [] + image_list = traverse_all_files(dir_name, image_list) + image_list = sorted(image_list, key=lambda file: -os.path.getctime(os.path.join(dir_name, file))) num = 48 if tabname != "extras" else 12 - max_page_index = len(file_list) // num + 1 + max_page_index = len(image_list) // num + 1 page_index = max_page_index if page_index == -1 else page_index + step page_index = 1 if page_index < 1 else page_index page_index = max_page_index if page_index > max_page_index else page_index idx_frm = (page_index - 1) * num - file_list = file_list[idx_frm:idx_frm + num] - #print(f"Loading history page {page_index}") + image_list = image_list[idx_frm:idx_frm + num] image_index = int(image_index) - if image_index < 0 or image_index > len(file_list) - 1: + if image_index < 0 or image_index > len(image_list) - 1: current_file = None - hide_image = None + hidden = None else: - current_file = file_list[int(image_index)] - hide_image = os.path.join(dir_name, current_file) - return [os.path.join(dir_name, file) for file in file_list], page_index, file_list, current_file, hide_image, "" + current_file = image_list[int(image_index)] + hidden = os.path.join(dir_name, current_file) + return [os.path.join(dir_name, file) for file in image_list], page_index, image_list, current_file, hidden, "" + def first_page_click(dir_name, page_index, image_index, tabname): return get_recent_images(dir_name, 1, 0, image_index, tabname) def end_page_click(dir_name, page_index, image_index, tabname): @@ -85,6 +88,10 @@ def show_images_history(gr, opts, tabname, run_pnginfo, switch_dict): dir_name = opts.outdir_img2img_samples elif tabname == "extras": dir_name = opts.outdir_extras_samples + d = dir_name.split("/") + dir_name = d[0] + for p in d[1:]: + dir_name = os.path.join(dir_name, p) with gr.Row(): renew_page = gr.Button('Renew Page', elem_id=tabname + "_images_history_renew_page") first_page = gr.Button('First Page') @@ -109,19 +116,20 @@ def show_images_history(gr, opts, tabname, run_pnginfo, switch_dict): img_file_name = gr.Textbox(label="File Name", interactive=False) with gr.Row(): # hiden items - img_path = gr.Textbox(dir_name, visible=False) + + img_path = gr.Textbox(dir_name.rstrip("/") , visible=False) tabname_box = gr.Textbox(tabname, visible=False) image_index = gr.Textbox(value=-1, visible=False) set_index = gr.Button('set_index', elem_id=tabname + "_images_history_set_index", visible=False) filenames = gr.State() - hide_image = gr.Image(type="pil", visible=False) + hidden = gr.Image(type="pil", visible=False) info1 = gr.Textbox(visible=False) info2 = gr.Textbox(visible=False) # turn pages gallery_inputs = [img_path, page_index, image_index, tabname_box] - gallery_outputs = [history_gallery, page_index, filenames, img_file_name, hide_image, img_file_name] + gallery_outputs = [history_gallery, page_index, filenames, img_file_name, hidden, img_file_name] first_page.click(first_page_click, _js="images_history_turnpage", inputs=gallery_inputs, outputs=gallery_outputs) next_page.click(next_page_click, _js="images_history_turnpage", inputs=gallery_inputs, outputs=gallery_outputs) @@ -132,12 +140,12 @@ def show_images_history(gr, opts, tabname, run_pnginfo, switch_dict): #page_index.change(page_index_change, inputs=[tabname_box, img_path, page_index], outputs=[history_gallery, page_index]) #other funcitons - set_index.click(show_image_info, _js="images_history_get_current_img", inputs=[tabname_box, img_path, filenames], outputs=[img_file_name, image_index, hide_image]) + set_index.click(show_image_info, _js="images_history_get_current_img", inputs=[tabname_box, img_path, filenames], outputs=[img_file_name, image_index, hidden]) img_file_name.change(fn=None, _js="images_history_enable_del_buttons", inputs=None, outputs=None) delete.click(delete_image,_js="images_history_delete", inputs=[delete_num, tabname_box, img_path, img_file_name, page_index, filenames, image_index], outputs=[filenames, delete_num]) - hide_image.change(fn=run_pnginfo, inputs=[hide_image], outputs=[info1, img_file_info, info2]) + hidden.change(fn=run_pnginfo, inputs=[hidden], outputs=[info1, img_file_info, info2]) - #pnginfo.click(fn=run_pnginfo, inputs=[hide_image], outputs=[info1, img_file_info, info2]) + #pnginfo.click(fn=run_pnginfo, inputs=[hidden], outputs=[info1, img_file_info, info2]) switch_dict["fn"](pnginfo_send_to_txt2img, switch_dict["t2i"], img_file_info, 'switch_to_txt2img') switch_dict["fn"](pnginfo_send_to_img2img, switch_dict["i2i"], img_file_info, 'switch_to_img2img_img2img')