Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

347 lines
12KB

  1. using System.Text;
  2. using System.Text.Json;
  3. using ToolsServices;
  4. namespace Services.Fooocus
  5. {
  6. public static class FooocusService
  7. {
  8. #region Méthodes publiques
  9. #region Gestion des paramètres
  10. public static (string, string, string) LoadParametresGenerateImg()
  11. {
  12. LoggerService.LogInfo("FooocusService.LoadParametresGenerateImg");
  13. string url = "";
  14. string endpointv1 = "";
  15. string endpointv2 = "";
  16. try
  17. {
  18. if (File.Exists(FichiersInternesService.ParamsGenerateImg))
  19. {
  20. string[] lignes = File.ReadAllLines(FichiersInternesService.ParamsGenerateImg);
  21. if (lignes.Length > 0)
  22. url = lignes[0];
  23. if (lignes.Length > 1)
  24. endpointv1 = lignes[1];
  25. if (lignes.Length > 2)
  26. endpointv2 = lignes[2];
  27. }
  28. return (url, endpointv1, endpointv2);
  29. }
  30. catch
  31. {
  32. return ("", "", "");
  33. }
  34. }
  35. public static bool SaveParametresGenerateImg(string url, string endpointv1, string endpointv2)
  36. {
  37. LoggerService.LogInfo("FooocusService.SaveParametresGenerateImg");
  38. try
  39. {
  40. StringBuilder sb = new();
  41. sb.AppendLine(url);
  42. sb.AppendLine(endpointv1);
  43. sb.AppendLine(endpointv2);
  44. File.WriteAllText(FichiersInternesService.ParamsGenerateImg, sb.ToString());
  45. return true;
  46. }
  47. catch
  48. {
  49. return false;
  50. }
  51. }
  52. public static FooocusRequest_Text_to_Image LoadParametresFooocus()
  53. {
  54. LoggerService.LogInfo("FooocusService.LoadParametresFooocus");
  55. FooocusRequest_Text_to_Image param = new();
  56. try
  57. {
  58. if (File.Exists(FichiersInternesService.ParamsFooocus))
  59. {
  60. string[] lignes = File.ReadAllLines(FichiersInternesService.ParamsFooocus);
  61. if (lignes.Length > 0)
  62. param.negative_prompt = lignes[0];
  63. if (lignes.Length > 1)
  64. param.guidance_scale = double.Parse(lignes[1]);
  65. if (lignes.Length > 2)
  66. param.performance_selection = lignes[2];
  67. if (lignes.Length > 3)
  68. param.sharpness = double.Parse(lignes[3]);
  69. if (lignes.Length > 4)
  70. param.style_selections = lignes[4].Split(',', StringSplitOptions.RemoveEmptyEntries) // coupe sur les virgules
  71. .Select(s => s.Trim()) // enlève les espaces inutiles
  72. .ToArray();
  73. }
  74. return param;
  75. }
  76. catch
  77. {
  78. return param;
  79. }
  80. }
  81. public static bool SaveParametresFooocus(FooocusRequest_Text_to_Image param, List<string> ListeSelectedsStylesFooocus)
  82. {
  83. LoggerService.LogInfo("FooocusService.SaveParametresFooocus");
  84. try
  85. {
  86. StringBuilder sb = new();
  87. sb.AppendLine(param.negative_prompt);
  88. sb.AppendLine(param.guidance_scale.ToString());
  89. sb.AppendLine(param.performance_selection);
  90. sb.AppendLine(param.sharpness.ToString());
  91. sb.AppendLine(string.Join(", ", ListeSelectedsStylesFooocus));
  92. File.WriteAllText(FichiersInternesService.ParamsFooocus, sb.ToString());
  93. return true;
  94. }
  95. catch
  96. {
  97. return false;
  98. }
  99. }
  100. #endregion
  101. #region Interactions
  102. public static async Task<bool> IsFooocusActif()
  103. {
  104. LoggerService.LogInfo($"FooocusService.IsFooocusActif");
  105. try
  106. {
  107. (string baseUrl, _, _) = LoadParametresGenerateImg();
  108. if (baseUrl == "")
  109. {
  110. var msg = "Erreur de chargement des paramètres Fooocus.";
  111. LoggerService.LogWarning(msg);
  112. return false;
  113. }
  114. var url = $"{baseUrl}";
  115. using var client = new HttpClient { Timeout = TimeSpan.FromSeconds(360) };
  116. client.Timeout = TimeSpan.FromSeconds(30);
  117. var response = await client.GetAsync(url);
  118. LoggerService.LogDebug($"FooocusService.IsFooocusActif : {response.IsSuccessStatusCode}");
  119. return response.IsSuccessStatusCode;
  120. }
  121. catch (Exception ex)
  122. {
  123. LoggerService.LogError($"FooocusService.IsFooocusActif : False --> {ex.Message}");
  124. return false;
  125. }
  126. }
  127. public static async Task<List<string>> GetFooocusStylesAsync()
  128. {
  129. LoggerService.LogInfo("FooocusService.GetFooocusStylesAsync");
  130. (string baseUrl, _, _) = LoadParametresGenerateImg();
  131. var url = $"{baseUrl}/v1/engines/styles";
  132. if (url == "")
  133. {
  134. LoggerService.LogWarning("FooocusService.GetFooocusStylesAsync : URL de l'API de génération d'image non configurée.");
  135. var lst = new List<string>();
  136. lst.Add("URL de l'API de génération d'image non configurée.");
  137. return lst;
  138. }
  139. using var client = new HttpClient();
  140. var response = await client.GetAsync(url);
  141. response.EnsureSuccessStatusCode();
  142. var json = await response.Content.ReadAsStringAsync();
  143. // Le JSON est du type ["Fooocus V2","Random Style",...]
  144. var styles = JsonSerializer.Deserialize<List<string>>(json);
  145. return styles ?? new List<string>();
  146. }
  147. public static async Task<string> GenerateTextToImageWithIP(string promptFinal, List<string> imagesFullFilename)
  148. {
  149. LoggerService.LogInfo("FooocusService.GenerateTextToImageWithIP");
  150. (string baseUrl, _, string endpoint) = LoadParametresGenerateImg();
  151. //endpoint = "/v2/generation/text-to-image-with-ip";
  152. var images = new List<object>();
  153. double poidsTotal = 1.9;
  154. foreach (var img in imagesFullFilename)
  155. {
  156. poidsTotal = poidsTotal - 0.1;
  157. if (poidsTotal < 0.2)
  158. poidsTotal = 0.2;
  159. var uneImg = new
  160. {
  161. cn_img = Convert.ToBase64String(File.ReadAllBytes(img)),
  162. cn_stop = 0.5,
  163. cn_weight = poidsTotal,
  164. cn_type = "ImagePrompt"
  165. };
  166. images.Add(uneImg);
  167. }
  168. var requestBody = new
  169. {
  170. prompt = promptFinal,
  171. image_prompts = images.ToArray()
  172. };
  173. var url = $"{baseUrl}{endpoint}";
  174. using var client = new HttpClient { Timeout = TimeSpan.FromSeconds(360) };
  175. var json = JsonSerializer.Serialize(requestBody);
  176. var content = new StringContent(json, Encoding.UTF8, "application/json");
  177. // Envoi de la requête POST
  178. var response = await client.PostAsync($"{url}", content);
  179. response.EnsureSuccessStatusCode();
  180. // Lecture de la réponse JSON
  181. var responseJson = await response.Content.ReadAsStringAsync();
  182. // Désérialisation
  183. using var doc = JsonDocument.Parse(responseJson);
  184. var imageUrl = doc.RootElement[0].GetProperty("url").GetString();
  185. if (imageUrl == null)
  186. {
  187. return "";
  188. }
  189. imageUrl = imageUrl.Replace("http://127.0.0.1:8888", baseUrl);
  190. return $"{imageUrl}";
  191. }
  192. public static async Task<string> GenerateImageWithFooocus(FooocusRequest_Text_to_Image requestBody)
  193. {
  194. LoggerService.LogInfo("FooocusService.GenerateImageWithFooocus(requestBody)");
  195. try
  196. {
  197. (string baseUrl, string endpoint, _) = LoadParametresGenerateImg();
  198. var url = $"{baseUrl}{endpoint}";
  199. if (url == "")
  200. {
  201. LoggerService.LogWarning("FooocusService.GenerateImageWithFooocus : URL de l'API de génération d'image non configurée.");
  202. return "URL de l'API de génération d'image non configurée.";
  203. }
  204. using var client = new HttpClient { Timeout = TimeSpan.FromSeconds(360) };
  205. var json = JsonSerializer.Serialize(requestBody);
  206. var content = new StringContent(json, Encoding.UTF8, "application/json");
  207. // Envoi de la requête POST
  208. var response = await client.PostAsync($"{url}", content);
  209. response.EnsureSuccessStatusCode();
  210. // Lecture de la réponse JSON
  211. var responseJson = await response.Content.ReadAsStringAsync();
  212. // Désérialisation
  213. using var doc = JsonDocument.Parse(responseJson);
  214. var imageUrl = doc.RootElement[0].GetProperty("url").GetString();
  215. if (imageUrl == null)
  216. {
  217. return "";
  218. }
  219. imageUrl = imageUrl.Replace("http://127.0.0.1:8888", baseUrl);
  220. return $"{imageUrl}";
  221. }
  222. catch (Exception ex)
  223. {
  224. LoggerService.LogError($"Erreur lors de la génération de l'image : {ex.Message}");
  225. return $"Erreur lors de la génération de l'image : {ex.Message}";
  226. }
  227. }
  228. public static async Task<string> GenerateImageWithFooocus(string prompt)
  229. {
  230. LoggerService.LogInfo("FooocusService.GenerateImageWithFooocus(prompt)");
  231. try
  232. {
  233. // Création du JSON à envoyer
  234. var requestBody = new FooocusRequest_Text_to_Image();
  235. if (File.Exists(FichiersInternesService.ParamsFooocus))
  236. {
  237. requestBody = LoadParametresFooocus();
  238. }
  239. requestBody.prompt = prompt;
  240. /*
  241. Lora lora1 = new Lora()
  242. {
  243. enabled = true,
  244. model_name = "sd_xl_offset_example-lora_1.0.safetensors",
  245. weight = 0.5
  246. };
  247. requestBody.loras.Append(lora1);
  248. */
  249. /*
  250. var requestBody = new
  251. {
  252. prompt = prompt,//"un chat steampunk sur un toit",
  253. negative_prompt = "blurry, low quality, distorted, watermark, text, extra limbs, cropped",
  254. guidance_scale = 9.0,
  255. StyleSelections = new string[0], // vide => pas d’expansion Fooocus V2
  256. performance_selection = "Quality",
  257. sharpness = 2.0,
  258. image_seed = -1,
  259. image_number = 1
  260. };
  261. */
  262. return await GenerateImageWithFooocus(requestBody);
  263. }
  264. catch (Exception ex)
  265. {
  266. LoggerService.LogError($"Erreur lors de la génération de l'image : {ex.Message}");
  267. return $"Erreur lors de la génération de l'image : {ex.Message}";
  268. }
  269. }
  270. #endregion
  271. #endregion
  272. }
  273. }