/
ToolManager.cs
706 lines (585 loc) · 22.7 KB
/
ToolManager.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.IO;
using System.Diagnostics;
using TMPro;
using UnityEngine.UI;
using System.Linq;
using UnityEngine.Events;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
public class ToolManager : MonoBehaviour
{
public static ToolManager Instance;
public static Settings s_settings;
public Setup setup;
public static History s_history = new History();
public static List<Template> s_liStyleTemplates = new List<Template>();
public static List<Template> s_liContentTemplates = new List<Template>();
public static List<string> s_liFavoriteGUIDs = new List<string>();
public static List<User> s_liUsers = new List<User>();
public static Dictionary<ImageInfo, List<object>> s_dictDisplayedBy = new Dictionary<ImageInfo, List<object>>();
public GameObject goImagePreviewPrefab;
public EndlessHistory endlessHistory;
public Color colorFavorite;
public Color colorButton;
public Canvas canvasMain;
public Canvas canvasTitle;
public Canvas canvasTooltips;
public static Texture2D s_texDefaultMissing { get => Instance.texDefaultMissing; }
public Texture2D texDefaultMissing;
public GameObject goWarning;
public TMP_Text textWarning;
public GameObject goWarningTriangle;
public GameObject goTextureBackground;
public GameObject goContextMenuWindowPrefab;
public Transform transContextMenuCanvas;
public GameObject goTooltipPrefab;
public Transform transTooltipCanvas;
public PaletteView paletteView;
public TextAsset textDefaultStyles;
// UI
public TMP_Text textFeedback;
public TMP_Text textVersion;
public Slider sliderUIScale;
// start button
public Button buttonStart;
public TMP_Text textStartButton;
public Image imageIconStart;
public Sprite spritePlay;
public Sprite spriteStop;
public Color colorPlay;
public Color colorStop;
public List<ImageInfo> liRequestQueue = new List<ImageInfo>(); // requester and prompt
private ImageInfo outputCurrentRequested;
public List<ImagePreview> liImagePreviews;
public GeneratorConnection genConnection;
public OptionsVisualizer options;
public GameObject goSelectPage;
public GameObject goLicensePage;
public GameObject goAboutPage;
public enum Page { Select, Install, Main, License }
public User userActive = new User();
public UnityEvent eventQueueUpdated = new UnityEvent();
public UnityEvent eventHistoryUpdated = new UnityEvent();
public UnityEvent<ImageInfo> eventHistoryElementDeleted = new UnityEvent<ImageInfo>();
private float fProcessingTime = 0f;
private float fLoadingTime = 0f;
private bool bKeepRequesting = false;
private string strWarningText = "";
private bool bWontWork = false;
void Awake()
{
Application.runInBackground = true;
StartCoroutine(ieCheckVersion());
s_liUsers.Add(userActive);
Instance = this;
Load();
}
public void RestoreHistory()
{
Debug.Log("Start history restore...");
// TODO: extend history, not replace it
// TODO: if part of prompt is a template, use it as template, not as prompt
s_history.MakeBackup();
//List<string> liImageFiles = Directory.GetFiles("E:/outputs_collection/aiimages/ghibli_bg/").ToList();
List<string> liImageFiles = Directory.GetFiles(s_settings.strOutputDirectory).ToList();
foreach (string strFilePath in liImageFiles)
{
if (s_history.liOutputs.Any(x => x.strFilePathRelative == Path.GetFileName(strFilePath)))
continue;
try
{
using (BinaryReader br = new BinaryReader(File.Open(strFilePath, FileMode.Open)))
{
// read the metadata by parsing the file as text, because reading the metafiles is surprisingly hard otherwise
var data = br.ReadChars((int)br.BaseStream.Length);
System.Text.StringBuilder sb = new System.Text.StringBuilder();
foreach (char c in data)
if ((int)c > 0) sb.Append(c.ToString()); else sb.Append(".");
string strFileAsString = sb.ToString();
int iStart = strFileAsString.IndexOf("{\"model\"");
if (iStart == -1) // no meta data found?
continue;
int iEnd = iStart;
int iBrackets = 0;
for (int i = iStart; i < strFileAsString.Length; i++)
{
if (strFileAsString[i] == '{')
iBrackets++;
else if (strFileAsString[i] == '}')
iBrackets--;
if (iBrackets == 0)
{
iEnd = i;
break;
}
}
// parse metadata as json
string strJson = strFileAsString.Substring(iStart, iEnd - iStart + 1);
JObject jobjMetaData = JObject.Parse(strJson);
JObject jobjImg = (JObject)jobjMetaData["image"];
ImageInfo imgInfo = new ImageInfo();
imgInfo.strGUID = Guid.NewGuid().ToString();
imgInfo.strFilePathRelative = Path.GetFileName(strFilePath);
imgInfo.prompt = new Prompt();
imgInfo.prompt.iWidth = (int)jobjImg["width"];
imgInfo.prompt.iHeight = (int)jobjImg["height"];
imgInfo.prompt.iSeed = (int)jobjImg["seed"];
imgInfo.prompt.strContentPrompt = jobjImg["prompt"][0]["prompt"].ToString();
imgInfo.prompt.fCfgScale = (float)jobjImg["cfg_scale"];
imgInfo.prompt.iSteps = (int)jobjImg["steps"];
s_history.liOutputs.Add(imgInfo);
}
}
catch (Exception ex)
{
Debug.Log($"Could not process image {strFilePath}, because: {ex.Message}");
}
}
s_history.Save();
Debug.Log("Finished history restore...");
}
private void Start()
{
Debug.Log(strGetWarningText());
bWontWork = strGetWarningText().Contains("Won't work");
if (bWontWork) // HACK
{
goWarning.SetActive(true);
textWarning.text += "\n" + strGetWarningText();
goWarningTriangle.SetActive(true);
goWarningTriangle.GetComponent<Tooltip>().strText = strWarningText;
}
// backward comp
string strSettingsPath = Path.Combine(Application.persistentDataPath, Settings.strSettingsName);
if (File.Exists(strSettingsPath) && !File.ReadAllText(strSettingsPath).Contains("bFreeGPUMemory"))
{
Debug.Log("Found old settings file. Setting firstStart again.");
s_settings.bIsFirstStart = true;
}
Startup();
StartCoroutine(ieAutoSave(120f));
StartCoroutine(ieStartDelayed());
}
private void Startup()
{
// FIRST STARTUP
if (s_settings.bIsFirstStart)
{
if (SystemInfo.graphicsDeviceName.ToLower().Contains("gtx 16") && SystemInfo.graphicsMemorySize < 4500)
{
UnityEngine.Debug.Log("Detected GTX 16XX with low VRAM. Switching to using FreeMemory mode.");
s_settings.bFreeGPUMemory = true;
s_settings.Save();
}
SetUIScale(Camera.main.pixelHeight / 1080f * 0.8f);
Setup.CreateDesktopShortcut();
LoadDefaultStyles();
}
if (!s_settings.bAcceptedLicense)
OpenPage(Page.License);
else
OpenPage(Page.Main);
s_settings.bIsFirstStart = false;
s_settings.Save();
//CreateWebBat();
}
public IEnumerator ieStartDelayed()
{
yield return null; // delay, so options don't overwrite it with their own init
if (s_history.liOutputs.Count > 0)
options.LoadOptions(s_history.liOutputs.Last());
}
void Update()
{
bool bButtonActive = genConnection.bInitialized;
if (bButtonActive != buttonStart.interactable)
buttonStart.interactable = bButtonActive;
if (!genConnection.bInitialized)
{
fLoadingTime += Time.deltaTime;
if (fLoadingTime < 200f)
textFeedback.text = $"Loading model. Please wait... ({fLoadingTime.ToString("0")}s) {(bWontWork ? strGetWarningText() : "")}";
else
textFeedback.text = $"<color=#FF0000>Loading model... ({fLoadingTime.ToString("0")}s) {(bWontWork ? strGetWarningText() : "")} - Ask for Discord support!</color>";
}
else if (genConnection.bProcessing)
{
fProcessingTime += Time.deltaTime;
textFeedback.text = $"Painting {(bKeepRequesting ? "forever + " : "")}{liRequestQueue.Count + 1}... {fProcessingTime.ToString("0.0")}s";
}
else
{
if (bKeepRequesting && liRequestQueue.Count == 0)
RequestImage();
if (liRequestQueue.Count > 0)
{
outputCurrentRequested = liRequestQueue.First();
outputCurrentRequested.eventStartsProcessing.Invoke(outputCurrentRequested);
genConnection.RequestImage(outputCurrentRequested, OnTextureReceived);
liRequestQueue.RemoveAt(0);
fProcessingTime = 0f;
eventQueueUpdated.Invoke();
}
else
{
textFeedback.text = "Ready!";
fLoadingTime = 0f;
}
}
}
public void OnTextureReceived(Texture2D _tex, string _strFilePathFull, bool _bWorked)
{
ImageInfo outputRequested = outputCurrentRequested;
outputRequested.SetTex(_tex);
outputRequested.fGenerationTime = fProcessingTime;
outputRequested.dateCreation = DateTime.UtcNow;
outputRequested.strFilePathRelative = _strFilePathFull.Replace(s_settings.strOutputDirectory, "");
outputRequested.strGpuModel = $"{SystemInfo.graphicsDeviceName} ({Mathf.RoundToInt(SystemInfo.graphicsMemorySize)} MB)";
outputRequested.iActualWidth = _tex.width;
outputRequested.iActualHeight = _tex.height;
if (_bWorked)
{
s_history.liOutputs.Add(outputRequested);
eventHistoryUpdated.Invoke();
}
if (!_bWorked)
{
liRequestQueue.Clear();
if (bKeepRequesting)
TogglePlay();
eventQueueUpdated.Invoke();
fLoadingTime = 0f;
}
outputRequested.eventStoppedProcessing.Invoke(outputRequested, _bWorked);
}
public void TogglePlay()
{
bKeepRequesting = !bKeepRequesting;
textStartButton.text = bKeepRequesting ? "Stop" : "Start";
imageIconStart.sprite = bKeepRequesting ? spriteStop : spritePlay;
ColorBlock colorBlock = buttonStart.colors;
colorBlock.normalColor = bKeepRequesting ? colorStop : colorPlay;
colorBlock.pressedColor = bKeepRequesting ? colorStop : colorPlay;
colorBlock.selectedColor = bKeepRequesting ? colorStop : colorPlay;
buttonStart.colors = colorBlock;
}
public void RequestImage()
{
UnityEngine.Debug.Log($"Starting preview for {options.promptGet(_bPreviewSteps:true, _bPreviewUpscale:true, _bPreviewFaceEnhance:true).strToString()}");
ImageInfo outputNew = new ImageInfo()
{
strGUID = Guid.NewGuid().ToString(),
prompt = options.promptGet(_bPreviewSteps: true, _bPreviewUpscale: true, _bPreviewFaceEnhance: true),
extraOptionsFull = options.extraOptionsGet(),
userCreator = userActive
};
RequestImage(outputNew);
}
public void RequestImage(ImageInfo _output)
{
liRequestQueue.Add(_output);
eventQueueUpdated.Invoke();
}
public string strGetWarningText()
{
if (!string.IsNullOrEmpty(strWarningText))
return strWarningText;
string strOutput = "";
strOutput += $"<b>Your graphics card</b>: {SystemInfo.graphicsDeviceName} ({Mathf.RoundToInt(SystemInfo.graphicsMemorySize / 1000f)} GB)\n";
int iWorks = 2; // yes, maybe, no
string strProblem = "";
if (SystemInfo.graphicsMemorySize < 3900)
{
iWorks = 0;
strProblem += "\nNot enough GPU memory. Needs at least 4 GB.";
}
if (SystemInfo.systemMemorySize < 11000)
{
iWorks = 0;
strProblem += "\nAI images needs at least 12 GB of memory (RAM).";
}
if (Application.dataPath.Contains(" "))
{
iWorks = 0;
strProblem += $"\nPath contains space! Make sure all folders above aiimages don't contain spaces. Path: {Application.dataPath}";
}
if (SystemInfo.graphicsDeviceName.ToLower().Contains("amd")
|| SystemInfo.graphicsDeviceName.ToLower().Contains("ati")
|| SystemInfo.graphicsDeviceName.ToLower().Contains("radeon"))
{
iWorks = 0;
strProblem += "\nAMD graphic cards won't work (yet). :(";
}
else if(SystemInfo.graphicsDeviceName.ToLower().Contains("intel"))
{
iWorks = 0;
strProblem += "\nYour PC appears to not have a dedicated graphics card. :(";
}
else if (!SystemInfo.graphicsDeviceName.ToLower().Contains("rtx 30")
&& !SystemInfo.graphicsDeviceName.ToLower().Contains("rtx 20")
&& !SystemInfo.graphicsDeviceName.ToLower().Contains("gtx 1"))
{
iWorks = Mathf.Min(iWorks, 1);
strProblem += "\nGPU is not the newest.";
}
if (!setup.bEverythingIsThere())
{
strProblem += "There are files missing. Try reinstalling the application if you encounter issues.";
iWorks = Mathf.Min(iWorks, 1);
}
if (iWorks == 2)
strOutput += "Should work! <3";
else if (iWorks == 1)
strOutput += "Might work! <3" + strProblem;
else if (iWorks == 0)
strOutput += "Won't work, most likely. :(" + strProblem;
strWarningText = strOutput;
return strOutput;
}
public void OpenPage(Page _page)
{
goSelectPage.SetActive(false);
goLicensePage.SetActive(false);
switch (_page)
{
case Page.Install:
setup.Open();
break;
case Page.Select:
goSelectPage.SetActive(true);
break;
case Page.Main:
if (!genConnection.bInitialized)
{
fLoadingTime = 0f;
textFeedback.text = "Loading model...";
genConnection.Init();
}
break;
case Page.License:
goLicensePage.SetActive(true);
break;
default:
break;
}
}
public void OpenOutputFolder()
{
Application.OpenURL($"file://{s_settings.strOutputDirectory}");
}
public void OpenTrashFolder()
{
Application.OpenURL($"file://{Path.Combine(s_settings.strOutputDirectory, "trashcan")}");
}
public void SetAboutPage(bool _bActive)
{
goAboutPage.SetActive(_bActive);
}
public void ShowSetup()
{
OpenPage(Page.Install);
}
public void ShowMainPage()
{
OpenPage(Page.Main);
}
public void Save()
{
s_settings.Save();
s_history.Save();
SaveData saveData = new SaveData()
{
liStyleTemplates = s_liStyleTemplates,
liContentTemplates = s_liContentTemplates,
liUsers = s_liUsers,
liFavoriteGUIDs = s_liFavoriteGUIDs,
palette = paletteView.palette
};
saveData.Save();
}
public void Load()
{
s_settings = Settings.Load();
s_history = s_history.Load();
SaveData saveData = SaveData.Load();
s_liStyleTemplates = saveData.liStyleTemplates;
s_liContentTemplates = saveData.liContentTemplates;
s_liUsers = saveData.liUsers;
s_liFavoriteGUIDs = saveData.liFavoriteGUIDs;
paletteView.Set(saveData.palette);
sliderUIScale.value = s_settings.fUIScale;
UpdateBackgroundTexture();
Directory.CreateDirectory(s_settings.strInputDirectory);
Directory.CreateDirectory(s_settings.strOutputDirectory);
Directory.CreateDirectory(Path.Combine(s_settings.strOutputDirectory, "favorites"));
options.optionSteps.UpdateLimit();
}
public void UpdateBackgroundTexture()
{
goTextureBackground.SetActive(s_settings.bUseBackgroundTexture);
}
public void OpenLicense()
{
Application.OpenURL("https://huggingface.co/spaces/CompVis/stable-diffusion-license");
}
public void DeleteImage(ImageInfo _img)
{
if (s_liFavoriteGUIDs.Contains(_img.strGUID))
{
Debug.Log("Cannot delete favorite images.");
return;
}
PreviewImage.Instance.SetVisible(false, null);
MoveToTrashFolder(_img);
DeleteFromHistory(_img);
}
public void MoveToTrashFolder(ImageInfo _img)
{
string strTrashFolder = Path.Combine(s_settings.strOutputDirectory, "trashcan");
Directory.CreateDirectory(strTrashFolder);
try
{
if (File.Exists(_img.strFilePathFull()))
File.Move(_img.strFilePathFull(), Path.Combine(strTrashFolder, Path.GetFileName(_img.strFilePathFull())));
}
catch
{
Debug.Log("Tried to delete file that is already in trash");
}
}
public void DeleteFromHistory(ImageInfo _img)
{
s_history.liOutputs.Remove(_img);
eventHistoryElementDeleted.Invoke(_img);
eventHistoryUpdated.Invoke();
}
public void SaveTemplate(ImageInfo _output, bool _bContent)
{
Template template = new Template()
{
strName = DateTime.Now.ToString("yyyy_MM_dd_hh_mm"),
strGUID = Guid.NewGuid().ToString(),
outputTemplate = _output
};
UnityEngine.Debug.Log($"Added {(_bContent ? "content" : "style")} template {template.strName}.");
if (_bContent)
s_liContentTemplates.Add(template);
else
s_liStyleTemplates.Add(template);
}
public void DeleteTemplate(Template _template, bool _bContent)
{
if (_bContent)
s_liContentTemplates.RemoveAll(x => x.strGUID == _template.strGUID);
else
s_liStyleTemplates.RemoveAll(x => x.strGUID == _template.strGUID);
}
public void OpenURL(string _strURL)
{
Application.OpenURL(_strURL);
}
public void AgreeLicense()
{
UnityEngine.Debug.Log("Agreed License");
s_settings.bAcceptedLicense = true;
s_settings.Save();
Startup();
}
public void OpenSettingsFolder()
{
Application.OpenURL($"File://{Application.persistentDataPath}");
}
public void Quit()
{
Application.Quit();
}
private void OnApplicationQuit()
{
Setup.RenewDesktopShortcut();
Save();
}
public static void AddDisplayer(ImageInfo _img, object _oDisplayer)
{
if (!s_dictDisplayedBy.ContainsKey(_img))
s_dictDisplayedBy.Add(_img, new List<object> { _oDisplayer });
else
{
if (!s_dictDisplayedBy[_img].Contains(_oDisplayer))
s_dictDisplayedBy[_img].Add(_oDisplayer);
}
}
public static void RemoveDisplayer(ImageInfo _img, object _oDisplayer)
{
if (!s_dictDisplayedBy.ContainsKey(_img))
{
UnityEngine.Debug.Log("Tried to remove displayer from imgInfo that doesn't have it.");
return;
}
s_dictDisplayedBy[_img].RemoveAll(x => x == _oDisplayer);
if (s_dictDisplayedBy[_img].Count == 0 && _img.bHasTexture() && _img.texGet() != s_texDefaultMissing)
Destroy(_img.texGet());
}
public IEnumerator ieCheckVersion()
{
UnityEngine.Networking.UnityWebRequest webRequest = UnityEngine.Networking.UnityWebRequest.Get("http://aiimag.es/data/version_newest.txt");
yield return webRequest.SendWebRequest();
if (webRequest.result != UnityEngine.Networking.UnityWebRequest.Result.Success)
{
UnityEngine.Debug.Log(webRequest.error);
textVersion.text = $"v{Application.version}";
yield break;
}
if (webRequest.downloadHandler.text == Application.version)
{
textVersion.text = $"up-to-date - v{Application.version}";
}
else
{
textVersion.text = $"<color=#00FF00>NEW AVAILABLE</color> - v{Application.version}";
}
}
private IEnumerator ieAutoSave(float _fEvery)
{
yield return new WaitForSeconds(_fEvery);
s_settings.Save();
StartCoroutine(ieAutoSave(_fEvery));
}
public void SetUIScale(float _fScale)
{
s_settings.fUIScale = _fScale;
canvasMain.scaleFactor = _fScale;
canvasTitle.scaleFactor = _fScale;
canvasTooltips.scaleFactor = _fScale;
endlessHistory.OnScaleUpdate();
}
public void LoadDefaultStyles()
{
List<Template> liDefaultStyles = JsonConvert.DeserializeObject<List<Template>>(textDefaultStyles.text);
s_liStyleTemplates.AddRange(liDefaultStyles);
//File.WriteAllText("default_styles_generated.txt", JsonConvert.SerializeObject(s_liStyleTemplates, Formatting.Indented));
}
public void CreateWebBat()
{
string strContent = "@echo off";
strContent += $"\ncall \"{ToolManager.s_settings.strAnacondaBatPath}\"";
strContent += $"\n{ToolManager.s_settings.strSDDirectory.Substring(0, 2)}";
strContent += $"\ncd \"{ToolManager.s_settings.strSDDirectory}\"";
strContent += "\nactivate ldm";
strContent += $"\nset \"TRANSFORMERS_CACHE={Application.dataPath}/../ai_cache/huggingface/transformers\"";
strContent += $"\nset \"TORCH_HOME={Application.dataPath}/../ai_cache/torch\"";
strContent += $"\npython scripts/dream.py --web";
strContent += "\nstart \"\" http://localhost:9090";
try
{
File.WriteAllText($"{Application.dataPath}/../start_web_version.bat", strContent);
}
catch
{
Debug.Log("Could not create web bat.");
}
}
}