This repository has been archived by the owner on Sep 12, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathExternalProcessRunner.cs
190 lines (167 loc) · 6.83 KB
/
ExternalProcessRunner.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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.ComponentModel;
namespace StableDiffusionGUI
{
public class GenerationProcessData
{
public Process? RunningGeneration { get; set; }
public Task? BackgroundRunner { get; set; }
public Thread? ErrorStream { get; set; }
public Thread? StandardStream { get; set; }
internal void Kill()
{
if(RunningGeneration != null)
{
StandardStream?.Interrupt();
ErrorStream?.Interrupt();
RunningGeneration.Kill();
RunningGeneration.WaitForExit();
RunningGeneration.Dispose();
}
}
}
/// <summary>
/// Handles running of python scripts through Anaconda
/// </summary>
public static class ExternalProcessRunner
{
public static GenerationProcessData? RunningGeneration { get; set; }
/// <summary>
/// Run a specific python process to generate images - either img2img or txt2img
/// </summary>
/// <param name="pythonProcess">Path to python process</param>
/// <param name="args">Argument chain (for example --prompt "..." --W 512 --H 512)</param>
/// <param name="callback">Called on process exit</param>
public static void Run(string pythonProcess, string args, Action<string> callback, Action<int> reportCallback, bool img2img = false)
{
RunningGeneration = new();
var task = Task.Run(() => BackgroundRun(pythonProcess, args, callback, reportCallback, img2img));
RunningGeneration.BackgroundRunner = task;
}
/// <summary>
/// Creates a process and threads listening to process' streams
/// </summary>
/// <param name="pythonProcess"></param>
/// <param name="args"></param>
/// <param name="callback"></param>
private static void BackgroundRun(string pythonProcess, string args, Action<string> callback, Action<int> reportProgress, bool img2img = false)
{
// preferences are already checked to not be empty/null ->
#pragma warning disable CS8602 // Dereference of a possibly null reference.
#pragma warning disable CS8604 // Possible null reference argument.
var workingDirectory = Directory.GetParent(new FileInfo(PersistentPreferencesData.Txt2ImgPath).DirectoryName).FullName;
#pragma warning restore CS8604 // Possible null reference argument.
#pragma warning restore CS8602 // Dereference of a possibly null reference.
// build the process that will silently start the console and redirect outputs
var process = new Process
{
EnableRaisingEvents = true,
StartInfo = new ProcessStartInfo
{
FileName = "cmd.exe",
RedirectStandardOutput = true,
RedirectStandardInput = true,
RedirectStandardError = !img2img,
UseShellExecute = false,
CreateNoWindow = !img2img, // windowless img2img is not working correctly for now
WorkingDirectory = workingDirectory,
}
};
process.Exited += (object? s, EventArgs args) =>
{
callback(workingDirectory);
RunningGeneration = null;
};
if(RunningGeneration != null)
RunningGeneration.RunningGeneration = process;
process.Start();
// Pass multiple commands to cmd.exe
using (var sw = process.StandardInput)
{
if (sw.BaseStream.CanWrite)
{
// Vital to activate Anaconda
var anaconda = PersistentPreferencesData.AnacondaPath.Replace("\\", "/");
sw.WriteLine($"{Path.Join(anaconda, "Scripts/activate.bat")}");
// Activate environment ldm
sw.WriteLine("activate ldm");
// run python script (txt2img or img2img)
var pythonFile = pythonProcess.Replace("\\", "/");//PersistentPreferencesData.Txt2ImgPath.Replace("\\","/");
sw.WriteLine($"python \"{pythonFile}\" {args}");
}
}
// move to new thread ->
ThreadStart stdThr = new(() => ListenOutput(process.StandardOutput));
ThreadStart errThr = new(() => ListenError(process.StandardError, reportProgress));
Thread std = new(stdThr);
Thread err = new(errThr);
std.Start();
if(!img2img)
err.Start();
if (RunningGeneration != null)
{
RunningGeneration.StandardStream = std;
RunningGeneration.ErrorStream = err;
}
}
/// <summary>
/// Read the stream until EOF
/// </summary>
/// <param name="process"></param>
private static void ListenOutput(StreamReader process)
{
// read multiple output lines
try
{
while (!process.EndOfStream)
{
var line = process.ReadLine();
Console.WriteLine(line);
}
}
catch (ThreadInterruptedException ex)
{
Console.WriteLine("\nStream interrupted: " + ex.Message);
}
}
private static void ListenError(StreamReader process, Action<int> report)
{
// read multiple output lines
try
{
while (!process.EndOfStream)
{
var line = process.ReadLine();
//Console.WriteLine(line);
// process the line for progress
if (!string.IsNullOrEmpty(line))
{
var match = Regex.Match(line, ".* {1,2}([0-9]*)%");
if (match.Success && match.Groups.Count > 1)
{
var percentage = match.Groups[1].Value;
if(int.TryParse(percentage, out var percentageValue))
report(percentageValue);
}
else
{
Console.WriteLine(line);
}
}
}
}
catch (ThreadInterruptedException ex)
{
Console.WriteLine("\nStream interrupted: " + ex.Message);
}
}
}
}