StringAutoTest.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. //
  2. // CharacterAutoTest.swift
  3. // KdanAuto
  4. //
  5. // Created by 朱东勇 on 2022/11/22.
  6. //
  7. import Foundation
  8. import Cocoa
  9. class CharacterAutoTest : AutoTest {
  10. // override func type() -> String {
  11. // return "PDFConvert_China_Auto_Test"
  12. // }
  13. override func name() -> String {
  14. return "字符转换准确率测试"
  15. }
  16. override func keys() -> NSArray {
  17. return ["字符", "快照"]
  18. }
  19. static var cSharedInstance = CharacterAutoTest()
  20. override class func shared() -> AutoTest? {
  21. return cSharedInstance
  22. }
  23. // Auto Test refrence Check File
  24. override func autoTest() {
  25. clearCacheFiles()
  26. let checkString = self.selectedKeys().contains("字符")
  27. let needCompare = self.selectedKeys().contains("快照")
  28. if !needCompare && !checkString {
  29. _status = .Finished
  30. return
  31. }
  32. _status = .Process
  33. reportString = NSMutableAttributedString.init(string: "\n【\(String(self.fileType())) - \(self.name())】字符比对开始!\n",
  34. attributes:[.foregroundColor : NSColor.blue])
  35. let files = DataModel.shared.originFilesFor(_fileType, type: _type)
  36. let checkDirectory = self.checkFileDirectory()
  37. let originDirectory = self.originFileDirectory()
  38. let resultDirectory = self.resultFileDirectory()
  39. for fileName in files {
  40. let fName = NSString(string: fileName).deletingPathExtension
  41. let originPath = NSString(string: originDirectory).appendingPathComponent(fName+".pdf")
  42. let resultPath = NSString(string: resultDirectory).appendingPathComponent(fName+"."+_extention)
  43. let checkPath = NSString(string: checkDirectory).appendingPathComponent(fName+"."+_extention)
  44. reportString?.append(NSMutableAttributedString.init(string: "\n【\(String(self.fileType())) - \(self.name())】开始转换文件 \"\(fName)\"\n",
  45. attributes:[.foregroundColor : NSColor.black]))
  46. // ...
  47. // 执行转换过程
  48. let convertSemaphore = DispatchSemaphore(value: 0)
  49. var success = false
  50. let convertQueue = DispatchQueue.global()
  51. convertQueue.async {
  52. success = FileConverter.shared().converter(originPath, inDesPath: resultPath)
  53. convertSemaphore.signal()
  54. }
  55. convertSemaphore.wait()
  56. if FileManager.default.fileExists(atPath: resultPath) && success {
  57. if checkString {
  58. // Load check file
  59. let checkData = NSData.init(contentsOfFile: checkPath) as! Data
  60. var documentAttributes:NSDictionary!
  61. let checkAttString = NSAttributedString.init(rtf: checkData, documentAttributes: &documentAttributes)
  62. var checkString = NSString(string: checkAttString!.string) as NSString
  63. let resultString = try? NSString.init(contentsOfFile: resultPath, encoding: NSUTF8StringEncoding)
  64. #if false
  65. //识别字符串 \shptxt\shptxt ... }
  66. let pageInfoStrings = resultString!.components(separatedBy: "\\shptxt\\shptxt") as NSArray
  67. var finalString = ""
  68. if pageInfoStrings.count > 0 {
  69. let subStrings = pageInfoStrings.subarray(with: NSMakeRange(1, Int(pageInfoStrings.count - 1))) as! [String]
  70. for pageInfoString in subStrings {
  71. let endRange = NSString(string: pageInfoString).range(of: "}")
  72. finalString = finalString.appending(NSString(string: pageInfoString).substring(to: endRange.location))
  73. }
  74. }
  75. //识别所有 【空格 ~ \】 之间的值,并进行缝合
  76. // Detect all strings between Spaces and \ and stitch
  77. let strings = finalString.components(separatedBy: " ")
  78. var resultStr = "" as NSString
  79. for str in strings {
  80. let markStr = str as NSString
  81. if (markStr.contains("\\f")) {
  82. let fRange = markStr.range(of: "\\f")
  83. let cRange = markStr.range(of: "\\c")
  84. let bRange = markStr.range(of: "\\b")
  85. let iRange = markStr.range(of: "\\i")
  86. let eRange = markStr.range(of: "\\e")
  87. let pRange = markStr.range(of: "\\p")
  88. let minPos = min(Int(fRange.location),
  89. Int(cRange.location),
  90. Int(bRange.location),
  91. Int(iRange.location),
  92. Int(eRange.location),
  93. Int(pRange.location))
  94. resultStr = resultStr.appending(markStr.substring(to: minPos)) as NSString
  95. }else {
  96. resultStr = resultStr.appending(markStr as String) as NSString
  97. }
  98. }
  99. resultStr = self.replaceUnicodeString(resultStr)
  100. #else
  101. let resultData = NSData.init(contentsOfFile: resultPath) as! Data
  102. var rDocumentAttributes:NSDictionary!
  103. let resultAttString = NSAttributedString.init(rtf: resultData, documentAttributes: &rDocumentAttributes)
  104. var resultStr = NSString(string: resultAttString!.string)
  105. #endif
  106. resultStr = resultStr.replacingOccurrences(of: "\n", with: "") as NSString
  107. checkString = checkString.replacingOccurrences(of: "\n", with: "") as NSString
  108. resultStr = resultStr.replacingOccurrences(of: " ", with: "") as NSString
  109. checkString = checkString.replacingOccurrences(of: " ", with: "") as NSString
  110. resultStr = resultStr.replacingOccurrences(of: "\\pard", with: "") as NSString
  111. resultStr = resultStr.replacingOccurrences(of: "\\par", with: "") as NSString
  112. // do { // save cache file for test
  113. // try? NSString(string: resultStr).write(toFile: NSString(string: DataModel.shared.resultPath()).appending("/\(self.name())-result-cache.txt"),
  114. // atomically: true, encoding: NSUTF8StringEncoding)
  115. //
  116. // try? NSString(string: checkString).write(toFile: NSString(string: DataModel.shared.resultPath()).appending("/\(self.name())-check-cache.txt"),
  117. // atomically: true, encoding: NSUTF8StringEncoding)
  118. // }
  119. let maxSize = checkString.length
  120. var successCount = 0;
  121. /**
  122. (A0 = B0)
  123. - A-1 & B-1
  124. (A0 != B0) & (A0 in B) & (B0 in A)
  125. - 取 A0,B0最小 Range 值
  126. - 字符串裁剪对齐
  127. (A0 != B0) & (A0 in B)
  128. - 存储B0到识别错误缓存
  129. (A0 != B0) & (B0 in A)
  130. - 存储 A0到识别遗漏字符串
  131. (A0 != B0)
  132. - 分别存储 A0、B0到遗漏及错误字串
  133. */
  134. var skipString = NSString()
  135. var failString = NSString()
  136. while (checkString.length > 0 && resultStr.length > 0) {
  137. let subc = checkString.substring(to: 1) as NSString
  138. let subr = resultStr.substring(to: 1) as NSString
  139. if subc.isEqual(to: subr) { // (A0 = B0)
  140. // Check Success
  141. appendErrorInfo(skipString, failString: failString)
  142. skipString = NSString()
  143. failString = NSString()
  144. checkString = checkString.substring(from:1) as NSString
  145. resultStr = resultStr.substring(from:1) as NSString
  146. successCount = successCount + 1
  147. }else if (checkString.contains(subr as String) && resultStr.contains(subc as String)) {
  148. appendErrorInfo(skipString, failString: failString)
  149. skipString = NSString()
  150. failString = NSString()
  151. let cRange = checkString.range(of: subr as String)
  152. let rRange = resultStr.range(of: subc as String)
  153. if (cRange.location < rRange.location) {
  154. let cacheString = checkString.substring(to:cRange.location + cRange.length)
  155. reportString?.append(NSMutableAttributedString.init(string: "对照字符串【\(cacheString)】未识别到\n",
  156. attributes:[.foregroundColor : NSColor.red]))
  157. checkString = checkString.substring(from:cRange.location) as NSString
  158. }else {
  159. let cacheString = resultStr.substring(to:rRange.location)
  160. reportString?.append(NSMutableAttributedString.init(string: "字符串【\(cacheString)】识别出错\n",
  161. attributes:[.foregroundColor : NSColor.red]))
  162. resultStr = resultStr.substring(from:rRange.location + rRange.length) as NSString
  163. }
  164. }else if (checkString.contains(subr as String)) {
  165. skipString = skipString.appending(subc as String) as NSString
  166. checkString = checkString.substring(from:1) as NSString
  167. }else if (resultStr.contains(subc as String)) {
  168. failString = failString.appending(subr as String) as NSString
  169. resultStr = resultStr.substring(from:1) as NSString
  170. }else {
  171. skipString = skipString.appending(subc as String) as NSString
  172. failString = failString.appending(subr as String) as NSString
  173. checkString = checkString.substring(from:1) as NSString
  174. resultStr = resultStr.substring(from:1) as NSString
  175. }
  176. }
  177. skipString = skipString.appending(checkString as String) as NSString
  178. failString = failString.appending(resultStr as String) as NSString
  179. appendErrorInfo(skipString, failString: failString)
  180. let degree = Float(successCount)/Float(maxSize) * 100
  181. var color = NSColor.black
  182. if fabs(degree-100.0) >= 0.01 {
  183. color = NSColor.red
  184. }
  185. reportString?.append(NSAttributedString.init(string: "【\(String(self.fileType())) - \(self.name())】文件 \"\(fName)\"比对完成,准确率\(degree)%(\(successCount)/\(maxSize))\n",
  186. attributes:[.foregroundColor : color]))
  187. }
  188. // compare screenshoot between result file with check file
  189. if needCompare {
  190. reportString?.append(NSMutableAttributedString.init(string: "【\(String(self.fileType())) - \(self.name())】文件 \"\(fName)\"快照生成中\n",
  191. attributes:[.foregroundColor : NSColor.black]))
  192. let rComparePath = NSString(string: resultDirectory).appendingPathComponent(fName+"_\(DataModel.shared.latestReportID()!).jpg")
  193. let cComparePath = NSString(string: checkDirectory).appendingPathComponent(fName+".jpg")
  194. let processThumbSemaphore = DispatchSemaphore(value: 0)
  195. var processSuccess = false
  196. let thumbnailQueue = DispatchQueue.global()
  197. thumbnailQueue.async {
  198. processSuccess = ProcessThumbnal.process(resultPath, desPath: rComparePath, outputSize: CGSize.init(width: 2048, height: 2048))
  199. if (processSuccess &&
  200. FileManager.default.fileExists(atPath: rComparePath)) {
  201. let degree = self.compareJPEG(rComparePath, checkPath: cComparePath)
  202. if degree == -1 {
  203. self.reportString?.append(NSMutableAttributedString.init(string: "【\(String(self.fileType())) - \(self.name())】文件 \"\(fName)\"快照对比失败,生成快照失败或无比对文件\n",
  204. attributes:[.foregroundColor : NSColor.red]))
  205. }else {
  206. var color = NSColor.black
  207. if fabs(degree-100.0) >= 0.01 {
  208. color = NSColor.red
  209. }
  210. self.reportString?.append(NSMutableAttributedString.init(string: "【\(String(self.fileType())) - \(self.name())】文件 \"\(fName)\"快照对比完成,图像相似度 \(degree)%\n",
  211. attributes:[.foregroundColor : color]))
  212. }
  213. }else {
  214. self.reportString?.append(NSMutableAttributedString.init(string: "【\(String(self.fileType())) - \(self.name())】文件 \"\(fName)\"快照生成失败\n",
  215. attributes:[.foregroundColor : NSColor.red]))
  216. }
  217. processThumbSemaphore.signal()
  218. }
  219. processThumbSemaphore.wait()
  220. }
  221. }else {
  222. reportString?.append(NSMutableAttributedString.init(string: "【\(String(self.fileType())) - \(self.name())】文件 \"\(fName)\"转档失败!\n",
  223. attributes:[.foregroundColor : NSColor.red]))
  224. }
  225. }
  226. NSLog("\(reportString)")
  227. _status = .Finished
  228. }
  229. func appendErrorInfo(_ skipString:NSString, failString: NSString) {
  230. if skipString.length > 0 && failString.length > 0 {
  231. reportString?.append(NSMutableAttributedString.init(string: "对比字符串【\(skipString)】错识别为【\(failString)】\n",
  232. attributes:[.foregroundColor : NSColor.red]))
  233. }else if (skipString.length > 0) {
  234. reportString?.append(NSMutableAttributedString.init(string: "对比字符串【\(skipString)】未识别到\n",
  235. attributes:[.foregroundColor : NSColor.red]))
  236. }else if failString.length > 0 {
  237. reportString?.append(NSMutableAttributedString.init(string: "字符串【\(failString)】识别出错\n",
  238. attributes:[.foregroundColor : NSColor.red]))
  239. }
  240. }
  241. func replaceUnicodeString(_ string:NSString) -> NSString {//中
  242. let items = string.components(separatedBy: "\\u") as [NSString]
  243. var resultString = NSString()
  244. for item in items {
  245. if (item.contains("?")) {
  246. let unicodeValue = item.intValue
  247. let skipRange = item.range(of: "?")
  248. let nextString = item.substring(from: Int(skipRange.location + skipRange.length)) as NSString
  249. let bytes : [UInt8] = [UInt8(unicodeValue/256),UInt8(unicodeValue%256)]
  250. let data = NSData.init(bytes: bytes, length: 2)
  251. let unicodeString = NSString.init(data: data as Data, encoding: NSUnicodeStringEncoding)! as NSString
  252. resultString = resultString.appending(String("\(unicodeString)\(nextString)")) as NSString
  253. }else {
  254. resultString = resultString.appending(String(item)) as NSString
  255. }
  256. }
  257. return resultString
  258. }
  259. }