StringAutoTest.swift 18 KB

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