__init__.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. # coding: utf-8
  2. #
  3. """
  4. import uiautomator2 as u2
  5. import uiautomator2.ext.ocr as ocr
  6. u2.plugin_add("ocr", ocr.OCR)
  7. d = u2.connect()
  8. d.ext_ocr("对战模式").click()
  9. """
  10. import requests
  11. import time
  12. API = ""
  13. class OCRObjectNotFound(Exception):
  14. pass
  15. class OCR(object):
  16. def __init__(self, d):
  17. """
  18. Args:
  19. d: uiautomator2 instance
  20. """
  21. self._d = d
  22. if not API:
  23. raise EnvironmentError("set API var before using OCR")
  24. def all(self):
  25. rawdata = self._d.screenshot(format='raw')
  26. r = requests.post(API, files={"file": ("tmp.jpg", rawdata)})
  27. r.raise_for_status()
  28. resp = r.json()
  29. assert resp['success']
  30. result = []
  31. for item in resp['data']:
  32. lx, ly, rx, ry = item['coords']
  33. x, y = (lx + rx) // 2, (ly + ry) // 2
  34. ocr_text = item['text']
  35. result.append((ocr_text, x, y))
  36. result.sort(key=lambda v: (v[2], v[1]))
  37. return result
  38. def __call__(self, text):
  39. return OCRSelector(self, text)
  40. class OCRSelector(object):
  41. def __init__(self, server, text=None, textContains=None):
  42. self._server = server
  43. self._d = server._d
  44. self._text = text
  45. self._text_contains = textContains
  46. def all(self):
  47. result = []
  48. for (ocr_text, x, y) in self._server.all():
  49. matched = False
  50. if self._text == ocr_text: # exactly match
  51. matched = True
  52. elif self._text_contains and self._text_contains in ocr_text:
  53. matched = True
  54. if matched:
  55. result.append((ocr_text, x, y))
  56. return result
  57. def wait(self, timeout=10):
  58. """
  59. Args:
  60. timeout: seconds to wait
  61. Returns:
  62. List of recognition (text, x, y)
  63. Raises:
  64. OCRObjectNotFound
  65. """
  66. deadline = time.time() + timeout
  67. first = True
  68. while first or time.time() < deadline:
  69. first = False
  70. all = self.all()
  71. if all:
  72. return all
  73. raise OCRObjectNotFound(self._text)
  74. def click(self, timeout=10):
  75. result = self.wait(timeout=timeout)
  76. _, x, y = result[0]
  77. self._d.click(x, y)
  78. if __name__ == '__main__':
  79. import uiautomator2.ext.ocr as ocr
  80. import uiautomator2 as u2
  81. d = u2.connect()
  82. print(ocr.OCR(d)("王者峡谷").click())