StringAutoTest.swift 21 KB

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