OrganIdentificationService.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. using AI.Common;
  2. using AI.Common.Log;
  3. using AI.DiagSystem;
  4. using AIDiagnosis.Common.Enums;
  5. using AIDiagnosis.Common.Models;
  6. using AIDiagnosisSDK.Enums;
  7. using System;
  8. using System.Collections.Concurrent;
  9. using System.Collections.Generic;
  10. using System.IO;
  11. using System.Linq;
  12. using System.Threading;
  13. using Vinno.AI.CommonSDK.Enums;
  14. using Vinno.AI.CommonSDK.Models;
  15. using Vinno.AI.CommonSDK.Tools;
  16. using Vinno.AI.OrganIdentificationSDK.Interfaces;
  17. using Vinno.AI.OrganIdentificationSDK.Models;
  18. using Vinno.AI.OrganIdentificationService.Tools;
  19. using Vinno.AI.Service.Common.Interfaces;
  20. using Vinno.AI.Service.Common.Models;
  21. using Vinno.AI.Service.Common.Tools;
  22. namespace Vinno.AI.OrganIdentificationService
  23. {
  24. public class OrganIdentificationService : IOrganIdentificationService, IDisposable, IEngine
  25. {
  26. private readonly ConcurrentStack<byte[]> _singleImageCache;
  27. private readonly string _modelFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Networks");
  28. private PipeServer _singleImagePipeServer;
  29. private ImageProvider _imageProvider;
  30. private AIDiagnosisSDK.AIDiagnosis _organIndentification;
  31. private bool _disposed;
  32. public static List<FunctionInfo> AllFunctions { get; }
  33. static OrganIdentificationService()
  34. {
  35. AllFunctions = AIDiagnosisSDK.AIDiagnosis.AllFunctions.Where(x => x.FunctionName == EnumAIDiagnosisFunction.OrganIdentification.ToString()).ToList();
  36. }
  37. public static void Init(FunctionInfo enableFunction, FunctionInfo currentUsedFunction)
  38. {
  39. AIDiagnosisSDK.AIDiagnosis.InitForOrganIdentification(enableFunction, currentUsedFunction);
  40. }
  41. public OrganIdentificationService()
  42. {
  43. try
  44. {
  45. _singleImageCache = new ConcurrentStack<byte[]>();
  46. _singleImagePipeServer = new PipeServer(AIDiagnosisSystemConsts.PipeForOrganIdentificationSingleImage);
  47. _singleImagePipeServer.LogMsgThrow += OnLogMsgThrow;
  48. _singleImagePipeServer.DataReceived += OnDataReceived;
  49. _singleImagePipeServer.StartAndReceive();
  50. _imageProvider = new ImageProvider(AIEnumType.OrganIdentification);
  51. }
  52. catch (Exception ex)
  53. {
  54. Logger.Error($"OrganIdentificationService-Constructor error:{ex}");
  55. }
  56. }
  57. private void OnLogMsgThrow(object sender, AILogEventArgs e)
  58. {
  59. if (e == null)
  60. {
  61. return;
  62. }
  63. switch (e.LogType)
  64. {
  65. case AIEnumLogType.ErrorLog:
  66. case AIEnumLogType.FatalLog:
  67. Logger.Error(e.Msg);
  68. break;
  69. case AIEnumLogType.WarnLog:
  70. Logger.Warning(e.Msg);
  71. break;
  72. case AIEnumLogType.InfoLog:
  73. default:
  74. Logger.Info(e.Msg);
  75. break;
  76. }
  77. }
  78. public void Initialize(OrganIdentificationParameter organIndentificationParameter, bool hasImageProvider)
  79. {
  80. try
  81. {
  82. CloseDiagnosis();
  83. var performance = (EnumPerformance)organIndentificationParameter.Performance;
  84. var detectMode = (EnumDetectMode)organIndentificationParameter.DetectMode;
  85. var isCropped = organIndentificationParameter.IsCropped;
  86. var detectTps = organIndentificationParameter.DetectTps;
  87. var intervalTime = organIndentificationParameter.IntervalTime;
  88. _organIndentification = new AIDiagnosisSDK.AIDiagnosis(EnumAIModule.OrganIdentification, Setting.Instance.IsSaveDetectImage, Setting.Instance.IsSaveAllImage, Logger.LogDir, hasImageProvider ? _imageProvider : null, performance, detectMode, isCropped, detectTps, intervalTime, _modelFolder, false, false, Setting.Instance.CorrectAIResults, Setting.Instance.IsIntelligentIdentificationMode, Setting.Instance.IntelligentIdentificationThreshold, Setting.Instance.IntelligentIdentificationTimeRange, false);
  89. _organIndentification.StartEvaluation += OnStartEvaluation;
  90. _organIndentification.FinishEvaluation += OnFinishEvaluation;
  91. _organIndentification.NotifyError += OnNotifyError;
  92. _organIndentification.NotifyLog += OnNotifyLog;
  93. }
  94. catch (Exception ex)
  95. {
  96. Logger.Error($"OrganIdentificationService-Initialize error:{ex}");
  97. }
  98. }
  99. /// <summary>
  100. /// 切换引擎
  101. /// </summary>
  102. /// <param name="functionInfo"></param>
  103. public void SwitchEngines(FunctionInfo functionInfo)
  104. {
  105. try
  106. {
  107. AIDiagnosisSDK.AIDiagnosis.SwitchAIEngines(functionInfo);
  108. if (_organIndentification != null)
  109. {
  110. _organIndentification.SwitchAIEngines2(functionInfo);
  111. }
  112. }
  113. catch (Exception ex)
  114. {
  115. Logger.Error($"OrganIdentificationService-SwitchEngines error:{ex}");
  116. }
  117. }
  118. public void Start()
  119. {
  120. try
  121. {
  122. if (_organIndentification != null)
  123. {
  124. _organIndentification.Start();
  125. }
  126. }
  127. catch (Exception ex)
  128. {
  129. Logger.Error($"OrganIdentificationService-Start error:{ex}");
  130. }
  131. }
  132. public void Stop()
  133. {
  134. try
  135. {
  136. if (_organIndentification != null)
  137. {
  138. _organIndentification.Stop();
  139. }
  140. }
  141. catch (Exception ex)
  142. {
  143. Logger.Error($"OrganIdentificationService-Stop error:{ex}");
  144. }
  145. }
  146. private void OnStartEvaluation(object sender, EventArgs e)
  147. {
  148. NotificationSender.SendNotification(new AINotificationArgs() { NotificationType = AIEnumNotificationType.OrganIndentificationStartEvaluationRaised, Params = e });
  149. }
  150. private void OnFinishEvaluation(object sender, global::AI.DiagSystem.AIDiagResultPerImg e)
  151. {
  152. var transAIDiagresultPerImg = AIConvertHelper.ConvertAIDiagResultPerImgToTransAIDiagResultPerImg(e);
  153. NotificationSender.SendNotification(new AINotificationArgs() { NotificationType = AIEnumNotificationType.OrganIndentificationFinishEvaluationRaised, Params = transAIDiagresultPerImg });
  154. }
  155. private void OnNotifyError(object sender, ErrorEventArgs e)
  156. {
  157. Logger.Error($"OrganIdentificationService OnNotifyError:{e.GetException()}");
  158. var logEventArgs = AICommonServiceConvertHelper.ConvertErrorEventArgsToAILogEventArgs(e);
  159. NotificationSender.SendNotification(new AINotificationArgs() { NotificationType = AIEnumNotificationType.OrganIndentificationNotifyLogRaised, Params = logEventArgs });
  160. }
  161. private void OnNotifyLog(object sender, LogEventArgs e)
  162. {
  163. if (e == null)
  164. {
  165. return;
  166. }
  167. switch (e.LogType)
  168. {
  169. case EnumLogType.InfoLog:
  170. Logger.Info($"OrganIdentificationService OnNotifyLog:{e.Msg}");
  171. break;
  172. case EnumLogType.WarnLog:
  173. Logger.Warning($"OrganIdentificationService OnNotifyLog:{e.Msg}");
  174. break;
  175. case EnumLogType.ErrorLog:
  176. case EnumLogType.FatalLog:
  177. default:
  178. Logger.Error($"OrganIdentificationService OnNotifyLog:{e.Msg}");
  179. break;
  180. }
  181. var logEventArgs = AICommonServiceConvertHelper.ConvertLogEventArgsToAILogEventArgs(e);
  182. NotificationSender.SendNotification(new AINotificationArgs() { NotificationType = AIEnumNotificationType.OrganIndentificationNotifyLogRaised, Params = logEventArgs });
  183. }
  184. public TransAIDiagResultPerImg DetectOneByteImage()
  185. {
  186. try
  187. {
  188. byte[] byteImage = null;
  189. int retryCount = 0;
  190. while (!_singleImageCache.TryPop(out byteImage) && retryCount < 50)
  191. {
  192. Thread.Sleep(10);
  193. retryCount++;
  194. }
  195. if (byteImage == null)
  196. {
  197. Logger.Error($"OrganIdentificationService-DetectOneByteImage Get Image Cache Fail");
  198. return null;
  199. }
  200. if (_organIndentification == null)
  201. {
  202. Logger.Error($"Detect One Byte Image Error:Organ Indentification is null");
  203. return null;
  204. }
  205. var result = _organIndentification?.DetectOneImage(byteImage);
  206. return AIConvertHelper.ConvertAIDiagResultPerImgToTransAIDiagResultPerImg(result);
  207. }
  208. catch (Exception ex)
  209. {
  210. Logger.Error($"OrganIdentificationService-DetectOneByteImage error:{ex}");
  211. return null;
  212. }
  213. }
  214. public TransAIDiagResultPerImg DetectOneRawImage(int height, int width, AIEnumColorType colorType)
  215. {
  216. try
  217. {
  218. byte[] byteImage = null;
  219. int retryCount = 0;
  220. while (!_singleImageCache.TryPop(out byteImage) && retryCount < 50)
  221. {
  222. Thread.Sleep(10);
  223. retryCount++;
  224. }
  225. if (byteImage == null)
  226. {
  227. Logger.Error($"OrganIdentificationService-DetectOneRawImage Get Image Cache Fail");
  228. return null;
  229. }
  230. if (_organIndentification == null)
  231. {
  232. Logger.Error($"Detect One Byte Image Error:Organ Indentification is null");
  233. return null;
  234. }
  235. var rawImage = new RawImage(byteImage, width, height, (EnumColorType)colorType);
  236. var result = _organIndentification?.DetectOneImage(rawImage);
  237. return AIConvertHelper.ConvertAIDiagResultPerImgToTransAIDiagResultPerImg(result);
  238. }
  239. catch (Exception ex)
  240. {
  241. Logger.Error($"OrganIdentificationService-DetectOneRawImage error:{ex}");
  242. return null;
  243. }
  244. }
  245. public void SetIsCropped(bool isCropped)
  246. {
  247. try
  248. {
  249. if (_organIndentification != null)
  250. {
  251. _organIndentification.IsCropped = isCropped;
  252. }
  253. }
  254. catch (Exception ex)
  255. {
  256. Logger.Error($"OrganIdentificationService-SetIsCropped error:{ex}");
  257. }
  258. }
  259. public void SetDetectTps(int detectTps)
  260. {
  261. try
  262. {
  263. if (_organIndentification != null)
  264. {
  265. _organIndentification.DetectTps = detectTps;
  266. }
  267. }
  268. catch (Exception ex)
  269. {
  270. Logger.Error($"OrganIdentificationService-SetDetectTps error:{ex}");
  271. }
  272. }
  273. public void SetIntervalTime(int intervalTime)
  274. {
  275. try
  276. {
  277. if (_organIndentification != null)
  278. {
  279. _organIndentification.IntervalTime = intervalTime;
  280. }
  281. }
  282. catch (Exception ex)
  283. {
  284. Logger.Error($"OrganIdentificationService-SetIntervalTime error:{ex}");
  285. }
  286. }
  287. public void SetDetectMode(AIEnumDetectMode detectMode)
  288. {
  289. try
  290. {
  291. if (_organIndentification != null)
  292. {
  293. _organIndentification.DetectMode = (EnumDetectMode)detectMode;
  294. }
  295. }
  296. catch (Exception ex)
  297. {
  298. Logger.Error($"OrganIdentificationService-SetDetectMode error:{ex}");
  299. }
  300. }
  301. public void Close()
  302. {
  303. try
  304. {
  305. Logger.Info($"OrganIdentificationService-Close Invoke");
  306. CloseDiagnosis();
  307. }
  308. catch (Exception ex)
  309. {
  310. Logger.Error($"OrganIdentificationService-Close error:{ex}");
  311. }
  312. }
  313. private void CloseDiagnosis()
  314. {
  315. if (_organIndentification != null)
  316. {
  317. _organIndentification.StartEvaluation -= OnStartEvaluation;
  318. _organIndentification.FinishEvaluation -= OnFinishEvaluation;
  319. _organIndentification.NotifyError -= OnNotifyError;
  320. _organIndentification.NotifyLog -= OnNotifyLog;
  321. _organIndentification.Close();
  322. _organIndentification = null;
  323. }
  324. }
  325. public void Dispose()
  326. {
  327. try
  328. {
  329. if (!_disposed)
  330. {
  331. Logger.Info($"OrganIdentificationService-Start Dispose");
  332. CloseDiagnosis();
  333. if (_singleImagePipeServer != null)
  334. {
  335. _singleImagePipeServer.DataReceived -= OnDataReceived;
  336. _singleImagePipeServer.Dispose();
  337. _singleImagePipeServer.LogMsgThrow -= OnLogMsgThrow;
  338. _singleImagePipeServer = null;
  339. }
  340. _imageProvider.Dispose();
  341. _imageProvider = null;
  342. _disposed = true;
  343. Logger.Info($"OrganIdentificationService Dispose End");
  344. }
  345. }
  346. catch (Exception ex)
  347. {
  348. Logger.Error($"OrganIdentificationService-Dispose error:{ex}");
  349. }
  350. }
  351. /// <summary>
  352. /// Send Raw Image Data For Pipe
  353. /// </summary>
  354. /// <param name="height"></param>
  355. /// <param name="width"></param>
  356. /// <param name="colorType"></param>
  357. public void SendRawImageData(int height, int width, AIEnumColorType colorType)
  358. {
  359. try
  360. {
  361. _imageProvider?.ReceiveRawImageData(height, width, (EnumColorType)colorType);
  362. }
  363. catch (Exception ex)
  364. {
  365. Logger.Error($"OrganIdentificationService-SendRawImageData error:{ex}");
  366. }
  367. }
  368. /// <summary>
  369. /// Send Byte Image Data For Pipe
  370. /// </summary>
  371. public void SendByteImageData()
  372. {
  373. try
  374. {
  375. _imageProvider?.ReceiveByteImageData();
  376. }
  377. catch (Exception ex)
  378. {
  379. Logger.Error($"OrganIdentificationService-SendByteImageData error:{ex}");
  380. }
  381. }
  382. /// <summary>
  383. /// 清除脏器识别的缓存
  384. /// </summary>
  385. public void ClearOrganIdentificationCache()
  386. {
  387. try
  388. {
  389. if (_organIndentification != null)
  390. {
  391. _organIndentification.ClearOrganIdentificationCache();
  392. }
  393. }
  394. catch (Exception ex)
  395. {
  396. Logger.Error($"OrganIdentificationService-ClearOrganIdentificationCache error:{ex}");
  397. }
  398. }
  399. private void OnDataReceived(object sender, byte[] e)
  400. {
  401. try
  402. {
  403. _singleImageCache.Push(e);
  404. }
  405. catch (Exception ex)
  406. {
  407. Logger.Error($"OrganIdentificationService-OnDataReceived error:{ex}");
  408. }
  409. }
  410. }
  411. }